10.22.2009

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.





comments powered by Disqus