iteration

Encapsulation

Episode Summary

This week we talk about encapsulated records, collections and replacing primitive objects.

Episode Notes

Episode 6 - More Code Examples

A weekly podcast about programming, development, and design through the lens of amazing books, chapter-by-chapter.

Encapsulate Record (162)

var organization = { name: "JP Sio", country: "USA" };

becomes ⬇️

class Organization {
  constructor(data) {
    this._name = data.name;
    this._country = data.country;
  }

  get name() {
    return this._name;
  }
  set name(arg) {
    this._name = arg;
  }

  get country() {
    return this._country;
  }
  set country(arg) {
    this._country = arg;
  }
}

Encapsulate Collection (170)

class Person {
  get courses() {
    return this._courses;
  }
  set courses(aList) {
    this._courses = aList;
  }
}

becomes ⬇️

class Person {
  get courses() {
    return this._courses.slice();
  }
  addCourse(aCourse) {
    /*...*/
  }
}

Replace Primative with Object (174)

orders.filter(0 => "high" === o.priority || "rush" === o.priority)

becomes ⬇️

orders.filter(o => o.priority.higherThan(new Priority("normal")));

A telephone number may be represented as a string for a while, but later it will need special behavior for formatting, extracting the area code, and the like

Inline Function (115) 🥴

Sometimes it's better to not try to split things apart, sometimes it just complicates things.

// before refactor: 

function getItemPrice(item) {
  if (itemOnSale(item) == true) {
    return item.price - 5
  } else {
    return item.price
  }
};

function itemOnSale(product) {
  if (product.onSale == true) {
    return true;
  } else {
    return false;
  }
};

let original = getItemPrice(sweatshirt);

// after refactor: 

function newGetItemPrice(item) {
  if (item.onSale == true) {
    return item.price - 5
  } else {
    return item.price
  }
};

Extract Class (182) 🥴


Picks