Alex Rivera | Logout

Java favorite refactoring techniques

Asked 2011-08-24T11:16:15.330
10

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.

Edit
Report

1 Answer

3
if (<some test>) {
    return someObject;
} else {
    return someOtherObject;
}

replace with:

if (<some test>) {
    return someObject;
}

return someOtherObject;

or for even more brevity and if the line isn't too long (ie you aren't creating the objects in-line):

return <some test> ? someObject : someOtherObject;

Guiding principles/patterns:

  • less code is good
  • redundant code is bad - when an if returns, there is no need for an "else"
  • less indentation is good
answered 2011-08-24T11:17:52.663

Your Answer