The Ideas Behind Every Pattern

How to tell that code has a problem, then three ideas that explain almost every pattern in the course. Learn them once, and each pattern after this is "that idea, applied here".

Updated

When Code Tells You Something's Wrong

  1. Code Smells: Symptom, Cause, Cure (Apprentice): Working code can still be hard to change, and it usually shows it: a code smell is a symptom you can see, like a cough, that points to a problem underneath; this lesson reads three smells in a food truck's ordering code as a doctor would, symptom, cause and cure, and shows why not every cure is a pattern.

The Three Ideas

  1. Find What Changes and Fence It Off (Apprentice): When the part of a program that changes every week is mixed into the part that shouldn't change, every change risks the rest; finding what changes and giving it a home of its own, behind one wall, is the idea behind almost every design pattern, and it comes with two words worth knowing: coupling and cohesion.
  2. Program to an Interface, Not a Class (Apprentice): When checkout asks for a card reader by name, every new way to pay means editing checkout; asking instead for "something that can take a payment", a promise any class can keep, lets a gift card, or anything else, plug in without checkout changing at all.
  3. Prefer Composition to Inheritance (Apprentice): When every combination of options becomes its own subclass, the classes multiply until a burrito with extra cheese and no onion needs a class of its own; building an item from parts it holds (composition) instead of from a family tree of subclasses (inheritance) turns each new option into one new part.

Exercise: The Food Truck Menu

  1. Exercise: The Food Truck Menu (Apprentice): Take Rosa's ticket: she wants to set the food truck's specials herself from the tablet, starting with taco Tuesday. Change the working menu code so a new special is a new piece of data, not an edit to the price code, with the tests green throughout.