(Not So) Stupid Questions 17: Should Code be Clean or D.R.Y.?
Editor's note: Sometimes the most interesting discussions begin when someone says, "This may be a stupid question, but ...." If the person asking the question has taken the time to think about the problem before asking, the question is often not stupid at all. The uncertainty points out an ambiguity in the specs, holes in the docs, or a search for how more experienced programmers might address a particular problem. From time to time, we will print one of the "(Not So) Stupid Questions" we receive and invite our readers to answer the question in the feedback section.
Remember that new people are joining the Java community all the time and may be looking for help from those with more experience. Also, those who began with Java as their first language can benefit from those coming to the community with experience in other languages. As always, answer the questions with kindness. You are also welcome to submit your questions to
This may be a stupid question, but ... "Should you prefer 'clean' code (e.g., sound object-oriented design) or D.R.Y. code?"
Say we have two unrelated base classes,
Vehicle. Both these classes have their own trees of subtypes (
Truck) and both also have fancy
toString() methods that use reflection to iterate over all their fields and build their
toString() code is generic and useful for their subtypes, but is also identical in both
Should you prefer:
- Leaving the few (say, dozen) lines of code duplicated in both
- Factoring the code into an artificial
ObjectWithGenericToStringbase class (i.e., breaking the logic of inheritance, but maintaining encapsulation)?
- Factoring the code into a static
ToStringUtilsclass (i.e., breaking encapsulation, but maintaining the logic of inheritance)?
- Factoring the code into a "uses" relationship and build a
ToStringManagersubsystem (i.e., maintaining encapsulation, but complicating the architecture just for a few lines)? Let us assume no third-party systems already exist for this (such as Commons Lang).
In general, I think c) is the right answer, but (assuming package-private is not an option, because
Vehicle are in different packages) this leads to general purpose "util" packages that border on functional programming.
Still, is it better to be D.R.Y. than clean?
|width="1" height="1" border="0" alt=" " />|