Lesson 23. Composition and forwarding

 

After reading lesson 23, you’ll be able to

  • Compose structures with composition
  • Forward methods to other methods
  • Forget about classical inheritance

When you look around the world, everything you see is made up of smaller parts. People tend to have bodies with limbs, which in turn have fingers or toes. Flowers have petals and stems. Mars Rovers have wheels and treads and entire subsystems, like the Rover Environmental Monitoring Station (REMS). Each part plays its role.

In the world of object-oriented programming, objects are composed of smaller objects in the same way. Computer scientists call this object composition or simply composition.

Gophers use composition with structures, and Go provides a special language feature called embedding to forward methods. This lesson demonstrates composition and embedding with a fictional weather report from REMS.

Consider this

Designing hierarchies can be difficult. A hierarchy of the animal kingdom would attempt to group animals with the same behaviors. Some mammals walk on land while others swim, yet blue whales also nurse their young. How would you organize them? It can be difficult to change hierarchies too, as even a small change can have a wide impact.

Composition is a far simpler and more flexible approach: implement walking, swimming, nursing, and other behaviors and associate the appropriate ones with each animal.

As a bonus, if you design a robot, the walking behavior can be reused.

23.1. Composing structures

23.2. Forwarding methods

23.3. Name collisions

Summary

sitemap