Skip to content

Instantly share code, notes, and snippets.

@marko-knoebl
Created October 15, 2022 13:54
Show Gist options
  • Save marko-knoebl/383942d1dc332a4d1c90119c924de5b8 to your computer and use it in GitHub Desktop.
Save marko-knoebl/383942d1dc332a4d1c90119c924de5b8 to your computer and use it in GitHub Desktop.

Clean Code

Names

use expressive variable / function names that describe what something is used for

NO:

for (let item of array) {
  // ...
}

YES:

for (let letter of remainingLetters) {
  // ...
}

Don't repeat yourself (DRY)

don't repeat yourself - use custom functions or loops instead

NO:

let posX = Math.ceil(Math.random() * 10);
let posY = Math.ceil(Math.random() * 10);
let posZ = Math.ceil(Math.random() * 10);

YES:

function randInt(limit) {
  return Math.ceil(Math.random() * limit);
}

let posX = randInt(10);
let posY = randInt(10);
let posZ = randInt(10);

NO:

let lotteryNumbers = [
  randInt(45),
  randInt(45),
  randInt(45),
  randInt(45),
  randInt(45),
  randInt(45),
];

YES:

let lotteryNumbers = [];
for (let i = 0; i < 6; i++) {
  lotteryNumbers.push(randInt(45));
}

Single responsibility principle (SRP)

A function should have a single responsibility

Pure functions

pure functions only interact with their environment by receiving parameters and returning values

reasons for using pure functions:

  • avoiding unintended data modification
  • easy to reuse

non-pure function: modifies the original:

let dataArray = [10, 4, -1, 7, -1];
removeNegativeEntries(dataArray);

console.log(dataArray); // [10, 4, 7]

pure function: returns new data:

let dataArray = [10, 4, -1, 7, -1];
let cleanedDataArray = removeNegativeEntries(dataArray);

console.log(dataArray); // [10, 4, -1, 7, -1]
console.log(cleanedDataArray); // [10, 4, 7]

Comments

NO: stating the obvoius

// multiply the mass by the velocity squared and divide by two
let energy = (mass * velocity ** 2) / 2;

YES: helpful comments

// formula taken from: https://en.wikipedia.org/wiki/Kinetic_energy
let energy = (mass * velocity ** 2) / 2;

YES: "documentation comments" for users of functions

/**
 * Compute the kinetic energy of a moving object (in Joules).
 * Parameters: mass (in kg), velocity (in m/s)
 */
function getKineticEnergy(mass, velocity) {
  return (mass * velocity ** 2) / 2;
}

Magic constants

extract "magic constants" to the top of the file

NO:

let lotteryNumbers = [];
for (let i = 0; i < 6; i++) {
  lotteryNumbers.push(randInt(45));
}

YES:

let MAX_NUMBER = 45;
let NUMBER_OF_DRAWS = 6;

// ...

let lotteryNumbers = [];
for (let i = 0; i < NUMBER_OF_DRAWS; i++) {
  lotteryNumbers.push(randInt(MAX_NUMBER));
}

"Main" functions

files should be made up of function definitions and possibly one main function call

function main() {
  foo();
  bar();
  // ...
}

function foo() {
  // ...
}

function bar() {
  // ...
}

main();

Resources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment