I have a util class that perform some work. Obviously, it is closed for extension and all methods are static. For the sake of simplicity, the class looks like this:
public final class Util {
private Util() { }
public static void doWork() {
// some work
int variable = help();
// some work uses variable
}
private static int help() {
// some helper functionality
}
}
The class has method doWork
that performs a lot of calculations. By the way, method calls helper method help
to obtain some result and rest of the code use the result returned by help
method.
Now, in client code I want to reuse functionality of method doWork
, but instead of calling help
I want to call help2
method. The simplest solution just create method doWork2
with replacing help
to help2
.
It is very bad approach, because every change in doWork
must be replicated in doWork2
either. This very similar to Template Method
pattern, but due to fact that we don't have extension here, we can't apply it.
Best solution I came up with to add parameter to this method, but preserve all existing users of doWork
:
public static void doWork() {
doWorkWithParameter(true);
}
public static void doWorkWithParameter(boolean helpOrHelp2) {
// some work
int variable = helpOrHelp2 ? help() : help2();
// some work uses variable
}
What are better design solutions can be applied to solve this problem? Is there a way to achieve flexibility like Template Pattern
has, but in application to util classes.
Thanks in advance.
public static void doWork() {...}
public static void doWork(boolean param) {...}
– Twocyclepublic static void doWork(int variable)
. Though I suspect the actual answer is that the confusion is due to the statics and that objects would provide a cleaner answer - difficult to tell with the abstract examples though. – Names