There are some common code patterns I find in other people's Java code that can benefit from some simple refactoring.
What are your pet code pattern hates and their fixes (and the reason if it isn't obvious)?
I have taken to liberty of answering with a couple of my own pet hates.
For many developers, the best moment to refactor is before working on a new version of the software or before adding new functionality. Cleaning up the code before adding new features to it improves the quality of the product itself and makes the job easier for other developers.
One of my favourite refactoring is using Strategy pattern instead of long if-else/switch statments. Eg.
String chooser = ""//some sting
if(testCond1(chooser)){
doSomething1();
} else if(testCond2(chooser)){
doSomethingElse2();
} else if(testCond2(chooser)){
doSomethingElse3();
} else if(testCond4(chooser)){
doSomethingElse4();
} else if(testCond5(chooser)){
doSomethingElse5();
} else if(testCond6(chooser)){
doSomethingElse6();
}
Can be changed to:
Map<String, Handler> handlers = new HashMap<String, Handler>();
handlers.get(chooser).handle();
then we define a Handler interface
interface Handler{
handle();
}
And for each condition we have a new class that implements the handler.
class CondOne implements Handler{
handle(){
//some code
}
}
Pros. Object oriented approch, code is easier to maintain. It is also easy to add new conditions without changing the important parts of the code.
I like enums and try to refactor code with a lot of string checks.
if (str.equals("A") {...}
else if (str.equals("B") {...}
else if (str.equals("C") {...}
to
switch (str){
case A: ... ; break;
case B: ... ; break;
case C: ... ; break;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With