Apply DeMorgan’s law refactoring

After reading up on some refactorings after a few hours of refactoring today, I thought it might be nice to share this refactoring with everyone.

I ran into some code today, a simple equality comparison method, except it was comparing about 7 properties, so even worse than this:

public bool Compare(item x, item y)
{
return !(x.a != y.a || x.b != y.b || x.c != y.c);
}

Even though it doesn’t take long to figure out what it is doing, it takes more time to figure out than if we applied DeMorgan’s law in what is known as avoiding double negatives refactoring:


public bool Compare(item x, item y)
{
return x.a == y.a && x.b == y.b && x.c == y.c;
}

Any time you run across code where you negate a set of conditions, do everyone else a favor and invert the conditions.  Apply DeMorgan’s law to make the code more readable. To freshen up on the rules, visit http://en.wikipedia.org/wiki/De_Morgan’s_laws.  Saving even 30 seconds of translation every time someone looks at that line of code, becomes a huge savings.

Advertisement

One Response to Apply DeMorgan’s law refactoring

  1. Rod says:

    Dude, Your looking at ETT code again aren’t ya.

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 )

Connecting to %s

Follow

Get every new post delivered to your Inbox.