DEV Community

Discussion on: The Fallacy of DRY

Collapse
 
rkfg profile image
rkfg

I'm not convinced that using inheritance to deduplicate code is bad. I did this in the past and it worked quite fine for me. No need to demonize the tool, it has its use and "prefer composition over inheritance" points to that as well. Prefer, but not stick to it forever. Composition also has its toll. You might need to supply the service from the outside (dependency injection), store it as a singleton or use a service locator. If the duplicated code isn't that big, the increased complexity of the approach is obvious.

I would say, it requires experience. In time, creating your own programs, maintaining them, looking at someone else's code will bring you there. You'd be able to choose the right way without going to extremes like "no inheritance anywhere!" or "dependency injection everywhere!" or "I saw that line already, I'm moving it into a function! No, to a separate class!".

Every tool is good for its own job.

Collapse
 
jeroendedauw profile image
Jeroen De Dauw

Fully agree that it takes experience to build good judgment and that there tend to be exceptions to rules.

I'm being a bit flippant about the code reuse via inheritance topic because I so often see people shoot themselves in the foot. There are times when it is a good choice though, but in my experience they do not occur often.

As to every tool being good for its own job: the thing with inheritance in most languages is that it does two completely different things: code reuse and sub-typing.

Anyway, that really is not what my post is about, and is a topic that takes more than a few short lines to do justice.