Java – Interpretation of DRY principle

designdryjava

Right now I'm struggling with this concept of DRY (Don't Repeat Yourself) in my coding. I'm creating this function in which I'm fearing it's becoming too complex but I'm trying to follow the DRY principle.

createTrajectoryFromPoint(A a,B b,C c,boolean doesSomething,boolean doesSomething2)

This function I have say takes 3 input parameters, and then the function will do something slightly different given the boolean combinations doesSomething and doesSomething2. However the problem I'm having is that this function is growing in complexity greatly with every new boolean parameter that's added.

So my question is, is it better to have a bunch of different functions that share a lot of the same logic (therefore violating the DRY principle) or one function that behaves slightly differently given a number of parameters but making it much more complex (but preserving DRY)?

Best Answer

boolean arguments to trigger different code paths in a single function/method is a terrible code smell.

What you are doing violates Loose Coupling and High Cohesion and Single Responsibility principles, which are much more important than DRY in precedence.

That means that things should depend on other things only when they have to ( Coupling ) and that they should do one thing and only one thing ( very well ) ( Cohesion ).

By your own omission, this is too tightly coupled ( all the boolean flags are a type of state dependency, which is one of the worst! ) and has too many individual responsibilities intermingled ( overly complex ).

What you are doing is not in the spirit of DRY anyway. DRY is more about repetition ( the R stands for REPEAT ). Avoiding copy and pasting is its most basic form. What you are doing isn't related to repetition.

Your problem is your decomposition of your code isn't at the correct level. If you think you will have duplicate code, then that should be its own function/method that is parameterized appropriate, not copy and pasted, and the others should be named descriptively and delegate to the core function/method.