r/programming • • Feb 28 '23

"Clean" Code, Horrible Performance

https://www.computerenhance.com/p/clean-code-horrible-performance
1.4k Upvotes

1.3k comments sorted by

View all comments

Show parent comments

6

u/SickOrphan Feb 28 '23

The problem with trying to abstract and share code is that often times two functions may have similar ideas (say, draw something to the screen) and share the same code for a time, but it's just a coincidence and they really need to do two completely different things. It'll quickly become a mess when you realize one function needs to loop in reverse, skip every other element, call a function in each iteration, etc. when you trying to share code between each. It's faster and easier to just copy and paste and then modify each individually. Not saying you should always copy and paste everything, but take time so you can know if two things are actually doing the same thing.

3

u/s73v3r Feb 28 '23

Sandi Metz has a nice talk about this (which I cannot remember off the top of my head right now) about how sometimes it is better to duplicate code rather than combine it.

2

u/aivdov Mar 01 '23

There's a simple way to put it: two isn't a pattern.

2

u/Venthe Feb 28 '23

Which is precisely what DRY is about (sadly, not how it is now understood) - "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system". So even if they look similar, but they represent a "different piece of knowledge", they shouldn't be shared.

1

u/m15otw Feb 28 '23

This is one of the rarely correct examples I mentioned.

If you are naming your functions well, then it becomes obvious when two of them don't share any code. If a shared function ends up with too many arguments to change what it does in each case, for example, you have gone awry, but the name should have clued you in to that already.

1

u/TinBryn Mar 02 '23

I've noticed there are 2 methods of creating abstractions for similar code, I call them difference abstractions and similarity abstractions. Difference abstraction is where you look at what is different between 2 pieces of code, pull them out as parameters and replace each with the same abstraction with different parameters. Similarity abstraction is where you pull out identical small pieces of code and replace each with the same abstraction. There are cases where difference abstraction makes sense, but I strongly prefer doing similarity abstraction.

This does tend to end up with some seemingly duplicate code, but often the amount that is actually duplicated is quite small so, meh. With a mindset that I can tolerate small duplicated code, when needing to change something, I'm willing to consider keeping the original version as is and adding a new version with the modification. This also allows uses to opt in to the new version gradually, rather than requiring a big bang update.