3 ms·
I have 2 rules I use when determining whether to duplicate code or to refactor: 1. How many duplications are there? If the code is duplicated once, that's fine
by lilyball 7y ago
I have 2 rules I use when determining whether to duplicate code or to refactor:
1. How many duplications are there? If the code is duplicated once, that's fine. If it's duplicated twice (so 3 instances of it), then it's time to consider refactoring, subject to the next rule.
2. Why is the code duplicated? If it's "incidental duplication", i.e. code that happens to look the same, don't refactor. Only refactor if there's actually a reason why the code is the same. Which is to say, attempt to predict the future: if a change is made to one instance of the code, do I expect it to be replicated to the other instances too?
- Hendrikto 7y ago> attempt to predict the future Sounds very error prone…
- marcus_holmes 7y agoThis. I wait until the feature is mature, and has been used by actual people. There's no point trying to clean up code that hasn't finished evolving, or that I don't understand fully. It also means I have a tidy stack of refactoring to do when I'm bored or need a quick motivational win :)
- lilyball 7y agoIt is, which is why you want to be conservative. If the duplicated code is obviously supposed to be identical, then predicting the future should be trivial. If it's not obvious, then it's a question of "can I conceive of a reason why I'd want to update one and not the others?". And if the answer is unclear, wait a while and see if anything comes up.
- jrumbut 7y agoIt's also useful to look at not just the duplication but the code itself. In this case, it was code for geometry which is not like to change all too much. Often the difference between harmless but ugly looking duplication and duplication that is actually harmful relies on the semantics of the code and not just its appearance.
- shkkmo 7y agoIt wasn't code for geometry, it was code for manipulating geometric shapes via UI. the article specifically mentions that custom behavior was eventually needed: > we later needed many special cases and behaviors for different handles on different shapes. My abstraction would have to become several times more convoluted to afford that, whereas with the original “messy” version such changes stayed easy as cake.