Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java favorite refactoring techniques [closed]

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.

like image 297
Bohemian Avatar asked Aug 24 '11 11:08

Bohemian


People also ask

What are the best practices for refactoring?

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.


2 Answers

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.

like image 120
gregory561 Avatar answered Sep 18 '22 15:09

gregory561


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;

}

like image 43
Farmor Avatar answered Sep 18 '22 15:09

Farmor