Graduate Program KB

Clean Code V1

Slides Recording

Contents

  • What is clean code
  • Common Principles and Rules-of-thumb
  • How TDD Helps
  • Peer Reviews
  • Key Lessons

What is Clean Code

  • Imagine walking into the shops and knowing where to go because there are signs telling you where product categories are. You are able to understand quickly where certain products are. This is what your codebase should look like.
  • Clean code is easy to read and understand. A clean codebase is organised in a way that developers will know where to look when implementing changes or fixing bugs.
  • This article will go through the common principles and rules-of-thumb that you can utilise in your day to day work.

Staying Clean and DRY

  • Don't
  • Repeat
  • Yourself
  • This principle is used to prevent duplication of code. If there is duplicated code, you will have the opportunity to apply abstraction. Instead of copy and pasting the same code everywhere, you could create a function to be called. Call the function twice instead of have executing the same code twice.

Boy Scout Rule

"Leave the campground cleaner than you found it"

  • Writing clean code once isn't enough, you need to keep it clean overtime. Everytime you work in an area of codebase make sure to clean up after yourself and also clean up the existing code.
  • You don't have to perform a spring clean each time, you could just make a variable name more expressive or break functions into smaller functions.
  • When you follow this rule, the code won't rot and will stay clean overtime.

Examples of Bad Code and Best Practices

// Takes 2 numbers a and b, adds them together and returns the output of that result
function sum(a, b) {
  return a + b;
}

const arr = [1, 2, 3];

let currentIndex = 0; // ii is set to 0

function printer(array){
  while (currentIndex < array.length) {
    console.log(array[currentIndex]); // Prints out element at index ii
    currentIndex++; // Increments ii
  }
}

// Multiply a number by 10
function multiply(x) {
  return x * 50;
}

function multiply2(x) {
  return x * 99;
}

function findMaxAndMultiplyBy10(x, y) {const topNumber = Math.max(x, y);return topNumber * 10;}

/* const multiply = (x,y) => {
  return y * x
}
*/

printer(arr) //1 2 3
console.log(sum(1,2)  === 3); //true
console.log(multiply(10) === 500); //true
console.log(multiply2(5) === 495); //true
console.log(findMaxAndMultiplyBy10(3,5) === 50); //true
  • Problems:
    • Bad comments
      • Outdated comments
      • Redundant comments
      • Commented out code
    • Bad names
      • Ambigious naming
      • Function names that don't reflect what they do
    • Functions
    • Formatting
  • Solutions:
    • Remove comments and make your namings more expressive
    • Remove commented out code and debugging code before merging to production
    • Rename variables and functions to reflect what they actually contain or do
    • Break down big functions into smaller functions
    • Use automated formatting tools like Prettier to format for you
    • Have a team standard for styling and formatting code
  • Tips:
    • Make sure to have tests running, to make sure the behaviour is unchanged
    • Don't remove the unfactored code while refactoring. Make a new function or variable with the same behaviour first then replace functionality with those new functions or variables.
  • Cleaned Code
// client.js
const utils = require('./utilities');
const arr = [1, 2, 3];

utils.printOutElementsOfArray(arr); //1 2 3
console.log(utils.addTwoNumbers(1, 2) === 3); //true
console.log(utils.multiplyTwoNumbers(10,50) === 500); //true
console.log(utils.multiplyTwoNumbers(5,99) === 495); //true

const maxNumber = utils.findMaxFromTwoNumbers(3,5)
console.log(utils.multiplyTwoNumbers(maxNumber,10) === 50); //true

// utilities.js
function printOutElementsOfArray(array) {
  for (let currentIndex = 0; currentIndex < array.length; currentIndex++) {
    console.log(array[currentIndex]);
  }
}

function addTwoNumbers(a, b) {
  return a + b;
}

function multiplyTwoNumbers(x, y) {
  return x * y;
}

function findMaxFromTwoNumbers(x, y) {
  return Math.max(x, y);
}

module.exports = { printer, multiplyTwoNumbers, sum, findMax };

Why TDD makes it easier to refactor

  • Imagine the previous code was 10x bigger and more complex. It would be hard to refactor all at once. so tdd is a way to prevent this from happening in the first place.
  • Test Driven Development focuses on 3 phases:
    1. Creating tests
    2. Implementation that passes tests
    3. Refactoring
  • Often developers spend a lot of time getting code to work, and will often refactor "later". Usually later means never because you either forgot what the code does or you move on to the next ticket.
  • What this process will enforce you to do is, cleaning up after yourself after each implementation
  • This is essential in a team environment, because what happens if you are not the one continuing with the implementation, you will have to pass the torch to someone else. That someone else, unless they are on the same wavelength as you, will be questioning your choices.

Peer Reviews

  • What you understand ≠ What other developers understand
  • Code Reviews: are a good opportunity to test if other people understood what you have done. This benefits both sides, the other person can learn how to do things differently and also teaches you different perspective to approach a solution.
  • Pair Programming: Similar to code reviews, instead of working by yourself and waiting for the other person to review. You can do it simultaneously

Lessons to Takeaway

  • Clean code benefits the long term, instead of opening a file and being forced to read through spaghetti code, you could be greeted with a clean file that explains everything to you.
  • Refactoring is an iterative process, you can't clean 100% on the first try. The code and always be cleaned in later iterations.
  • Continuous improvement not only for the codebase but for the developer professionally and technically
  • It is all up to you. Reading a book on how to cook, isn't going to make you the next Gordon Ramsey. You will have to be the one to practice and apply these processes.