The Object-Oriented Code You Need
The building blocks every pattern is made of, in all five languages. Learners who know them can take the chapter check first and skip ahead.
Updated
Objects
- Classes and Objects (Apprentice): A review of classes and objects in all five languages: a Snack class with fields, a constructor and methods, objects made from it, and the classic shape of a Java program you'll see in textbooks.
- Interfaces: A Promise Any Class Can Keep (Apprentice): When code is written for one class, every new kind of thing means a copy of that code; an interface writes down a promise (a name and a price for some hours) that any class can keep, so the code asks for the promise instead of the class, in C#, Java and TypeScript, with an abstract base class in Python and duck typing in JavaScript.
- Polymorphism: One Call, Many Behaviors (Apprentice): When the desk checks what kind of vehicle it has before it can price it, every new vehicle means another check, and a forgotten one prices it at $0; polymorphism moves each price into its own class, so one call, rental.price(hours), does the right thing for a bike, an e-bike and a scooter.
Putting Objects Together
- Inheritance and Composition: Is-a and Has-a (Apprentice): Two ways to build a class from another: inheritance, where an e-bike is a bike and overrides its price, and composition, where a bike has a lock it keeps as a field; saying the relationship aloud, is-a or has-a, tells you which one fits.
- Delegation: Handing the Job On (Apprentice): When every screen reaches through a rental to price its bike, a new rule such as a $2 helmet has to be added everywhere, and one place is missed; delegation gives the rental its own price() that hands the bike's part on to the bike, the move half the design patterns are built from.
- Functions as Values (Apprentice): A weekend discount as a true/false flag means the total's code changes with every new deal; functions as values let the caller hand in the rule instead: a function stored in a variable, passed to another function, or made and returned by one, in C#, Java, Python, JavaScript and TypeScript.
Exercise: The Bike Rental Desk
- Exercise: The Bike Rental Desk (Apprentice): Take a ticket from Pedal & Go's manager: scooters this week, a partner shop's kayaks next month, and weekend discounts that marketing keeps changing. Change the working rental desk so new kinds of rental and new deals arrive from outside, with the tests green throughout.