Skip to content

Instantly share code, notes, and snippets.

@JPBM135
Last active June 19, 2024 04:41
Show Gist options
  • Save JPBM135/17556b10038aa8586134fb72560536b0 to your computer and use it in GitHub Desktop.
Save JPBM135/17556b10038aa8586134fb72560536b0 to your computer and use it in GitHub Desktop.
Clean Code

Meaningful Names

Intention revealing names

- const d = '18/06/2024; // Date today
+ const dateToday = '18/06/2024;

Avoid variables with implicit meaning

// See in this case the list refers to a Set no an Array
- const aIdList = new Set([1,2,3,4,5]); 
// Now we don't need to worry about changing the name if the type changes
+ const accountsIds = new Set([1,2,3,4,5]); 

Make meaningful distinctions

Old

function findArrayDifference<T>(a1: T[], a2: T[]): T[] {
  const diffA1 = a1.filter((item) => !a2.includes(item));

  const diffA2 = a2.filter((item) => !a1.includes(item));

  return diffA1.concat(diffA2);
}

New

function findArrayDifference<T>(source: T[], destination: T[]): T[] {
  const differenceFromSource = source.filter((item) => !destination.includes(item));
   
  const differenceFromDestination = destination.filter((item) => !source.includes(item));
   
  return differenceFromSource.concat(differenceFromDestination);
}

Pronounceable names and Searchable names

Old

const acts = getActs();
const npActsIds = new Set();

for (const ac of acts) {
  if (ac.pst === 0) {
    npActsIds.add(ac.i)
  }
}

** New **

enum PaymentStatus {
  NotPaid,
  Paid,
}

/*
...
*/

const acounts = getAcounts();
const notPaidAccounts = new Set();

for (const account of accounts) {
  if (account.paymentStatus === PaymentStatus.NotPaid) {
    notPaidAccounts.add(account.id)
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment