Simple Rules

For Simple Code

Abbreviations

class Trnsltr {

}

You increased productivity by skipping 3 letters 👏

Abbreviations

class Translator {
  // ...
}

You increased productivity by skipping 3 letters 👏

Abbreviations: Function Names

class UserService {
  fetch (applicationId) {
    // ...
  }
}

Obviously you will always fetch users by their application id, duh!

Abbreviations: Function Names

class UserService {
  fetchByApplicationId (id) {
    // ...
  }
}

Abbreviations: Loops

for (let x of things) {
  // ...
}

for (let thing of things) {
  // ...
}

🛑

Abbreviations: Redundant Words

class Todo {
  updateTodo () {
    // ...
  }
}

const todo = new Todo();
todo.updateTodo();

class Todo {
  save () {
    // ...
  }
}

const todo = new Todo();
todo.save();

🛑

No Indentation

none if possible and 2 at most

function _getTargetNames(field, ruleSchema, ruleName) {
  if (ruleSchema.params) {
    const numTargets = ruleSchema.params.filter(param => param.isTarget).length;
    if (numTargets > 0) {
      const names = {};
      for (let index = 0; index < ruleSchema.params.length; index++) {
        const param = ruleSchema.params[index];
        if (param.isTarget) {
          const key = field.rules[ruleName][index];
          const name = field.names[key] || key;
          if (numTargets === 1) {
            names._target_ = name;
            break;
          } else {
            names[`_${param.name}Target_`] = name;
          }
        }
      }
      return names;
    }
  }
  return {};
}

On a scale from 1 to 10 how readable is this?

Indentation Extermination Toolbelt

  • Defensive Checking.
  • Early returns.
  • Combining Conditions.
  • Refactoring to functions.

Demo: Refactor

Never

Ever

Use `else`

Redundant else

How to spot it: The Guide

Redundant else telltales

  • return statements.
  • last else.

Refactoring Toolbelt

  • return statements.
  • throw statements.
  • refactoring to functions that return.

Demo: Refactor Exercise 2

async function process () {
  const user = new User();
  if (user.isActive) {
    const paymentMethod = await user.getPaymentMethod();
    if (paymentMethod) {
      if (paymentMethod.type === 'card') {
        const validated = await paymentMethod.checkCVC();
        if (!validated) {
          console.log('User did not type their CVC correctly');
          
          return false
        } else {
          await paymentMethod.pay(1200);
          await paymentMethod.finalize();

          return true;
        }
      } else if (paymentMethod.type === 'cash') {
        await paymentMethod.finalize();

        return true;
      }
    } else {
      console.log('User does not have a payment method');
      
      return false;
    }
  } else {
    console.log('User is not active');
    
    return false;
  } 
}

The Silver bullet

  • Early Returns
  • Happy Path at the Bottom

Thanks

Simple Rules

By Abdelrahman Awad

Simple Rules

  • 733