Piotr Gabryanczyk’s Blog

Java, Refactoring, AOP, Spring, DDD, TDD, etc.

  • Blogroll

    • I have joined Anti-IF Campaign

Refactoring – conditionals

Posted by Piotr Gabryanczyk on November 17, 2006

I came across such a code:

 1  private boolean checkForSymmetricNulls(Object lhs, Object rhs) {
 2         return (lhs == null) ? (rhs == null) : (rhs != null);
 3     }
 4 
 5     private boolean isSymmetricallyNullOrEquals(Object lhs, Object rhs) {
 6         if (checkForSymmetricNulls(lhs, rhs)) {
 7             if (lhs != null) {
 8                 return lhs.equals(rhs);
 9             }
10             return true;
11         }
12         return false;
13     }

I was trying to figure out what this does for good 5 minutes and I realized that isSymmetricallyNullOrEquals and checkForSymmetricNulls could be replaced with one method:

 1  private boolean equal(Object lhs, Object rhs) {
 2         if (lhs == null || rhs == null) return lhs == rhs;
 3         return lhs.equals(rhs);
 4  }

I simplified the code slightly and also used the following refactoring:

http://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html

but the following seem to be relevant:

http://www.refactoring.com/catalog/decomposeConditional.html

http://www.refactoring.com/catalog/consolidateConditionalExpression.html

http://www.refactoring.com/catalog/consolidateDuplicateConditionalFragments.html

Enjoy!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: