Good post! I personally prefer to repeat as needed better than one complex code with several conditions just to accommodate all known use cases. Repeat makes code easier to maintain and understand.
This is usually a sign that your abstractions are weak and you should consider refactoring the code around what's repeated, too. Often it means you have too little abstraction and too much specialization in your functions/classes/etc.
Though as Niels points out, you might be trying to de-duplicated code that's not truly duplicated. Always question the code first, but if you can't come up with a better abstraction, it may be best to leave it for another time. I do agree that a little duplication is better than an over-complicated abstraction. The goal is to consolidate the knowledge and authority to one implementation as much as is reasonable.
I agree! question the code first before abstracting code :)
If I understand you correctly you’re saying: if I abstract away code, but in that code I have to cater for a couple of different use cases the code inside the abstraction becomes too complex, right?
There’s two answers:
1: it could be that the code you’re trying to deduplicate is not similar enough, in that case don’t deduplicate.
2: there are ways (patterns) to make the code inside your abstractions less complex (basically: less conditionals). For a nice illustrated example of this: youtu.be/8bZh5LMaSmE
We're a place where coders share, stay up-to-date and grow their careers.
We strive for transparency and don't collect excess data.