Friday, April 18, 2008

 

Booleans Shouldn't Be Complicated

Warning: Geeky programmer content below.

While learning a new codebase, I was a little disturbed when I saw this:

  enum IsVerifying {
    IsVerifyingFalse,
    IsVerifyingTrue
  };

  enum IsVerified {
    IsVerifiedFalse,
    IsVerifiedTrue
  };

  enum IsEnabled {
    IsEnabledFalse,
    IsEnabledTrue
  };

  enum IsActive {
    IsActiveFalse,
    IsActiveTrue
  };

  enum IsOnline {
    IsOnlineFalse,
    IsOnlineTrue
  };

  /* etc. (There are about a dozen more of these.) */

And there was a lot of verbose code for dealing with these types, such as

  if (Verified()) {
    verified = IsVerifiedTrue;
  }
  else {
    verified = IsVerifiedFalse;
  }

  if (Enabled()) {
    enabled = IsEnabledTrue;
  }
  else {
    enabled = IsEnabledFalse;
  }

  /* etc. */

What's wrong with using plain-old-Boolean values false and true, or 0 and 1?

Well, after poking around the code more, I did find the reason that the original programmer did this. He has a lot of functions that take several flags as parameters, and something like this:

  SetStates(IsVerifyingFalse,
            IsVerifiedTrue,
            IsEnabledTrue,
            IsActiveFalse,
            IsOnlineFalse);

is easier to understand than something like this:

  SetStates(false, true, true, false, false);

But still, yyeeaagghh is the proper reaction to seeing something like this.


Comments: Post a Comment

<< Home

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