4 ms·
> Use composition instead. Inheritance was a hack in the first place. Composition is great. It's the preferred way. However, if you take it to the extreme (co
by alganet 1y ago
> Use composition instead. Inheritance was a hack in the first place.
Composition is great. It's the preferred way.
However, if you take it to the extreme (composition only, never inheritance) you sometimes end up with really weird meaningless objects that have only a single method and a one-to-one relationship with another object.
Private methods are ideal for making those abstractions easier to understand. A private method, therefore, is equivalent to an object that has a one-to-one relationship with another object (it's only composed there) and a single method.
A protected method is similar, but allows whoever subclasses it to replace that single one-to-one "mini object" inside with another one-to-one "mini object".
When used within this mindset, it greatly simplifies code. It lets you simplify a branch that has only a single leaf into something easier to read.
Together with classical refactorings (extract method, move method, extract class), they're a precious tool.
Of course, typing is a consideration as well, but I'm talking exclusively about their role in granularity control.
It is unecessary, but convenient. It can be misused. Composition can also be misused.
- tadfisher 1y ago> However, if you take it to the extreme (composition only, never inheritance) you sometimes end up with really weird meaningless objects that have only a single method and a one-to-one relationship with another object. We can take a cue from the functional languages and make this less code-smelly by using anonymous function types (e.g. lambdas). This removes the one issue with single-purpose/single-method objects, which is naming them.
- alganet 1y agoIt's an extra tool, for sure. There is no silver bullet. No one likes huge inheritance chains, no one likes only tiny lego pieces, no one likes callback hell.