Codele / Advanced programming
Composition: has-a instead of is-a
Family trees of classes get tangled fast. Often it is simpler to build an object out of small parts that you plug in and swap.
- Composition means building an object out of smaller objects it has: a Bird has a fly part and a swim part.
- Inheritance means is-a. It fits a true family, such as Dog is an Animal. For mixes of abilities it makes tangled trees.
- Parts can be swapped while the program runs, even on one bird. A family tree cannot change its mind like that.
- The bird passes the work on to its parts. This is called delegating: each part knows only its own job.
- Rule of thumb: prefer composition, and use inheritance only for a true is-a. Go has no inheritance, so building from parts is how Go is normally written. In Python and JavaScript, anything with an act() method can be plugged in, and nothing checks it beforehand.
Loading the playable lesson…