Programming foundations

Stage 5 · Lesson 2 of 10

Composition, inheritance and interfaces

Object-oriented design and clean code

There are two main ways to reuse behaviour between classes. says "is a": a SavingsAccount is an Account and inherits its methods. Composition says "has a": a Car has an Engine and calls it.

Prefer composition by default. Deep inheritance trees tie classes together, so a change to a parent can break its children in surprising ways. or abstract base classes let different classes share a contract, a promise of which methods they have, such as anything with a pay() method.

Python and JavaScript get the same effect with duck typing: if it has the method, it can be used. Your code can then work with any of them. That is polymorphism, and it lets you add a new payment type without editing the code that uses payments.

A question to check yourself, an AI practice session and 2 cheat sheet entries come when you add the roadmap to your account. Add it

Resources for this stage

Start with· follow one of these

Practise

  • Request mentoring on a solved exercise and ask specifically about naming and structure

Keep handy

  • One page from assertions to test fixtures, the most common C++ test framework

Also worth your time

Mark this stage as not done?