- Learning Functional Programming in Go
- Lex Sheehan
- 246字
- 2021-07-02 23:13:51
Summary
In this chapter, we saw how to use bad design using inheritance in Java and contrasted that solution to using composition in Go.
The Gang of Four's (GoF) epic book, Design Patterns: Elements of Reusable Object-Oriented Software, discussed design patterns that addressed design flaws in the object oriented languages like Java. For example, in the Putting Reuse Mechanisms to Work section, the GoF book states, Favor object composition over class inheritance.
This design principle is not even applicable to Go. Go does not support inheritance. No extra thought or work is required for Go developers. Go promotes composition out-of-the-box.
"These compositional techniques are what give Go its flavor, which is profoundly different from the flavor of C++ or Java programs."
- Rob Pike
Composition is a software design pattern we should use to build better APIs.
We start by breaking our system into small parts: single responsibility interfaces. We can then put the pieces back together again. When we architect our APIs using composition, our applications have a better chance to grow and adapt to the requirements that may change over time. Our applications become easier to reason about and maintain.
In the next chapter, we'll persist in our pursuit of good design and will focus on the decorator pattern. We'll study Go's Reader and Writer interfaces and see why less is more. We'll implement channels in order to control the life cycle of a concurrent program and much more.