5 ms·
Off the top of my head, there are two reasons people seem to de-duplicate code. One is because two or more things happen to share similar code. Another reason
by sbov 11y ago
Off the top of my head, there are two reasons people seem to de-duplicate code. One is because two or more things happen to share similar code. Another reason is because two or more things must share similar code.
It seems like you are speaking of the first reason. There is no dependency, and the programmer is creating one. IMHO you should have at least 3 instances before creating an abstraction to reduce your code.
The second reason is different though. By creating the abstraction you are not adding a dependency, you are making an implicit dependency explicit. There is a huge difference. In this instance any duplicate code is bad.
- Chris2048 11y agoI think that principle I've heard before called "1, 2, 3, abstract"; as in, wait until you see it at least three times before considering extraction. I'd also add - wait until the code is 'stable', i.e no longer under active architectural development, connected only to other stable parts (or with stable/authoritative interfaces) and having then existed in such a state for a continued period of varied usage. then refactor.
- Anchor 11y agoI'd say this is sound advice for core components of the system, but we may want also to consider the types of the dependencies. For example, I would not wait for three times if the dependency is some kind of external system (DB, UI, Network, MQ, OS, Library, Framework, or the like) which is volatile in one of the worst ways - not directly under your control, unlike your own source code.
- eva1984 11y agoAgree. Frequency matters. If it is used everywhere, no reason not to abstract.
- runT1ME 11y agoI have a third reason. Abstraction, or code de-duplication, if done right, ends up making code easier to reason about. The paper that made me rethink everything I knew is http://www.mpi-sws.org/~dreyer/tor/papers/wadler.pdf http://www.mpi-sws.org/~dreyer/tor/papers/wadler.pdf and explains this wonderfully.