Sponsored Link •
Sometimes code duplication is warranted, even good.
I read a lot that code duplication is bad, and that when we find it, we should refactor. In most cases, that's probably true, but not always. Sometimes code duplication is warranted, even good.
Consider a component that you are creating. You know there is another component available that has a small amount of behavior you'd like to use. You could reference that other component and avoid duplication. Is the benefit of avoiding code duplication worth the extra deployment dependency, complexity, and configuration issues that might be involved? It may not be.
Or how about when you'd like to use some of what a 3rd party component has to offer, but you don't want the dependency on the third party component because it carries with it quite a bit of overhead. Might you consider duplicating the code to avoid the heavyweight dependency? It's certainly a viable option, in my opinion.
Szyperski in Component Software states that "Although maximizing reuse has many oft-cited advantages, it has one substantial disadvantage - the explosion of context dependencies." And herein lies the rub with ideas such as the DRY principle. It is not universally applicable. No principle is actually. There will always be some condition that is grounds for violation of almost anything you've been told.
While principles, patterns, heuristics, and guidelines offer valuable advice about how to do things the right way, they don't serve as substitution for thinking on our own. Unfortunately, I think we all too often let these principles, etc. do the thinking for us.
|Kirk Knoernschild is a hands-on software consultant with over ten years of industry experience, and is passionate about using leading best practices to build better software. Kirk is the author Java Design: Objects, UML, and Process, published in 2002 by Addison-Wesley. He frequently contributes to various technical publications, and actively updates his personal website, www.kirkk.com, with new articles and whitepapers on a variety of software development topics. He is also the founder of www.extensiblejava.com, a growing resource of design pattern heuristics in Java.|