Re:Composition over Configuration
by cmwelsh on Wednesday April 10, 2019 @10:09PM
(#19630547)
A monk asked Java master Kaimu:
What is the “single-responsibility principle”?
Said Kaimu:
That a class shall do exactly one thing,
and do it completely.
The monk asked:
How shall I decide this “one thing”?
Said Kaimu:
The Fisherman does not build ships,
or we would call him a Shipwright.
The monk asked:
Is there no room in your philosophy for interfaces?
What if my class can serve as a Fisherman,
and a Shipwright and Sailor besides?
Said Kaimu:
What would you name such a three-headed monster?
The monk replied:
Shísho, after my uncle. He lives by the sea and does all these things.
Said Kaimu:
I would give your class Shísho three instance variables:
a Fisherman, a Shipwright, and a Sailor.
Then Shísho may implement those interfaces by delegation.
The monk replied:
I speak of inheritance, yet you answer in composition.
All of my uncle is a Fisherman, not just his left foot.
What use are objects, if we do not faithfully model the world?
Said Kaimu:
If I paint a fine shark upon this page, will you say, “Fine shark!”
or will you complain that it is flat and does not eat you?
The monk asked:
But how are we to know when the flat shark is shark enough?
Or when our uncle should fish with his left foot?
Said Kaimu:
Learning how is our “single reponsibility”.
Said Kaimu: That a class shall do exactly one thing, and do it completely.
The monk asked: How shall I decide this “one thing”?
Said Kaimu: The Fisherman does not build ships, or we would call him a Shipwright.
The monk asked: Is there no room in your philosophy for interfaces? What if my class can serve as a Fisherman, and a Shipwright and Sailor besides?
Said Kaimu: What would you name such a three-headed monster?
The monk replied: Shísho, after my uncle. He lives by the sea and does all these things.
Said Kaimu: I would give your class Shísho three instance variables: a Fisherman, a Shipwright, and a Sailor. Then Shísho may implement those interfaces by delegation.
The monk replied: I speak of inheritance, yet you answer in composition. All of my uncle is a Fisherman, not just his left foot. What use are objects, if we do not faithfully model the world?
Said Kaimu: If I paint a fine shark upon this page, will you say, “Fine shark!” or will you complain that it is flat and does not eat you?
The monk asked: But how are we to know when the flat shark is shark enough? Or when our uncle should fish with his left foot?
Said Kaimu: Learning how is our “single reponsibility”.
- “Flat Shark”
http://thecodelesscode.com/case/175