reading-notes

Aloysious' Codefellows Reading Notes

View the Project on GitHub

Code 301 Reading Notes

Class 09

<== Previous Lesson Next Lesson ==>

<== Home 🏠

📷 Image: Source

Functional Programming Concepts

Functional programming is a programming paradigm :

a style of building the structure and elements of computer programs

that treats computation as the evaluation of mathematical functions

and avoids changing-state and mutable data — Wikipedia

Pure functions

Immutability

When data is immutable, its state cannot change after it’s created.

If you want to change an immutable object, you can’t.

Instead, you create a new object with the new value.

📷 Image: Source

Refactoring Javascript for Readability source

Strategies:

Here are some straightforward to implement methods that can lead to easier to read code.

There are no absolutes when it comes to clean code — there’s always an edge case!

Return early from functions:

function showProfile(user) {
  if (user.authenticated === true) {
    // ..
  }
}

// Refactor into ->

function showProfile(user) {
  // People often inline such checks
  if (user.authenticated === false) { return; }
  // Stay at the function indentation level, plus less brackets
}

Cache variables so functions can be read like sentences:

function searchGroups(name) {
  for (let i = 0; i < continents.length; i++) {
    for (let j = 0; j < continents[i].length; j++) {
      for (let k = 0; k < continents[i][j].tags.length; k++) {
        if (continents[i][j].tags[k] === name) {
          return continents[i][j].id;
        }
      }
    }
  }
}

// Refactor into ->

function searchGroups(name) {
  for (let i = 0; i < continents.length; i++) {
    const group = continents[i]; // This code becomes self-documenting
    for (let j = 0; j < group.length; j++) {
      const tags = group[j].tags;
      for (let k = 0; k < tags.length; k++) {
        if (tags[k] === name) {
          return group[j].id; // The core of this nasty loop is clearer to read
        }
      }
    }
  }
}

Check for Web APIs before implementing your own functionality:

function cacheBust(url) {
  return url.includes('?') === true ?
    `${url}&time=${Date.now()}` :
    `${url}?time=${Date.now()}`
}

// Refactor into ->

function cacheBust(url) {
  // This throws an error on invalid URL which stops undefined behaviour
  const urlObj = new URL(url);
  urlObj.searchParams.append('time', Date.now); // Easier to skim read
  return url.toString();
}

Reading

<== Home 🏠