The one thing about refactoring
People often get wrong. You should be totally ok with this. The best you can get is to get wrong in 1 of 4 times. But the reality tends to be something worse. You may not have full information about your problem, or there is some chaotic relationship. All this stuff can raise your probability to get wrong to the 3 of 4 times.
When we do programming, most of the time we are trying to defeat the complexity that is pushing on the project. There is a good way to defeat it: to find a good abstraction. Abstractions help to make our code maintainable and consistent. But given the rule above, a probability of getting abstraction wrong is kind of big. You really have to THINK to get good abstraction.
You may even introduce new abstraction accidentally, by generalizing some duplicate code. There is a rule called DRY, which is the acronym for “Don’t Repeat Yourself”. I’ve found it a very dangerous rule to apply. By generalizing some code, you are coupling the parts of the code that never have to be coupled. After you get new requirements, the best you can do is to realize that your abstraction is wrong and try to undo it. It is relatively easy to generalize some code, but it is tremendously hard to “un-generalize” it back. Think of factoring a big number into primes.
It may even get worse if a guy who tries to apply new requirements is not you. There is 99% chance that he will try to fit new requirements into the old abstraction.
So what to do with all of this? I want this to be your takeaway thoughts from this short article:
- If you are not sure about your generalization/refactoring — do not do it. If you leave it as is you will give a chance for a person after you to get it right. Maybe he will be you in future.
- Think twice before adding new abstraction — bad abstraction is worse than its absence.
