(Not So) Stupid Questions 17: Should Code be Clean or D.R.Y.? Blog

Version 2


    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?"

    First Thoughts

    Say we have two unrelated base classes, Fruit andVehicle. Both these classes have their own trees of subtypes (Apple, Banana,Car, Truck) and both also have fancytoString() methods that use reflection to iterate over all their fields and build their toString()s. ThetoString() code is generic and useful for their subtypes, but is also identical in both Fruit andVehicle.

    Should you prefer:

    1. Leaving the few (say, dozen) lines of code duplicated in bothFruit and Vehicle?
    2. Factoring the code into an artificialObjectWithGenericToString base class (i.e., breaking the logic of inheritance, but maintaining encapsulation)?
    3. Factoring the code into a static ToStringUtilsclass (i.e., breaking encapsulation, but maintaining the logic of inheritance)?
    4. Factoring the code into a "uses" relationship and build aToStringManager subsystem (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 Fruit andVehicle 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?