Wednesday, October 12, 2005

 

Think Positive

Code such as the following leaves readers scratching their heads:

  if IsNotUninhibited() != true then
    DoSomething()
  else
    DoSomethingElse()
  end

Under what circumstances does DoSomething() get called? Well, it obviously has something to do with whether something is "inhibited" or not, but with all those negations mixed in, it's hard to tell if DoSomething() gets executed when inhibited or when not inhibited.

When I find something like this, I try to refactor it into something easier to understand by eliminating the excess negations. Here are some of the principles I follow:

So if we follow these principles, the above code could be rewritten as

  if IsEnabled() then
    DoSomething()
  else
    DoSomethingElse()
  end

Would you fail to deny the rewrite isn't not a lot less unclear?


Comments:
That makes a great mini-tutorial! I think I subconsiously do the same things, but never put all the steps down as a procedure. I'll be passing this along to some other programmers that I work with.
 
Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?