Refactoring For Reusability: Day Seven of "The Complete Node.js Developer Course"

View this thread on: d.buzz | hive.blog | peakd.com | ecency.com
·@matthewdavid·
0.000 HBD
Refactoring For Reusability: Day Seven of "The Complete Node.js Developer Course"
![photo5012998412878063555.jpg](https://steemitimages.com/DQmNW1WwVdQtYZzdndvrgRiYgiNLJmh2RU2wBshmHbiPvJj/photo5012998412878063555.jpg)

## Missing: the normal picture of myself holding a laptop 

It was dark outside before I thought about taking a picture today. So you get to have a snap of just my laptop screen instead.

## More complexity, for simplicity's sake

The course is starting to become a little harder for me to follow. In this section, the first part was really easy to follow what was going on. It was actually about simplicity and refactored the code previously  inside the ```addNote``` function to separate functions outside so they could be reused in other note functions later on.

And that did make sense. Here are those two generalized functions:

```
var fetchNotes = () => {
  try {
    var notesString = fs.readFileSync('notes-data.json')
    return JSON.parse(notesString)
  } catch (e) {
    return []
  }
}

var saveNotes = (notes) => {
  fs.writeFileSync('notes-data.json', JSON.stringify(notes))
}
```
### Reusability 

Now the ```fetchNotes``` and ```saveNotes``` functions can be used inside the other note action functions later on.

### Section Challenge 

I was able to complete the challenge and it worked, but it was noticeably different than the solution given by the instructor. There's a lot going on here and this is where I struggle with how much to explain in a Steemit post. I don't want to talk through everything in a section line by line, but rather give you the general idea. 

My solution, which worked:

```
if (command === 'add') {
  var note = notes.addNote(argv.title, argv.body);
  if (note === undefined) {
    console.log(
      'Note title taken. Try another title.'
    )
  } else if (note.title === argv.title) {
    console.log('---')
    console.log(`Title: ${note.title} :: Note Added`)
    console.log(`Body: ${note.body}`)
  }
```
### Instructors Solution

 The instructors solution started with:

```if (note) { ... }``` 

I was a little confused by this and it took me a while to figure out how it worked. I'm still a little fuzzy. You also don't see all the code from the other notes.js file. But essentially, the other code returns **note** if the addNote function worked and the note title was note a duplicate. ```if (note)``` then just checks to see if **note** was returned and then does it's thing. I did a check to see if **note** was undefined first. 

## Section completed

Thanks for following my progress. Please let me know if these posts are making sense and are helpful. If you are also learning node.js, what kind of writing are you looking for?

In any case...

### Thanks for reading!

--- @matthewdavid
👍 , , , , , , , , , , , , , , ,