nullybool == true

It’s always been a pet peeve of mine to see conditions where a boolean variable is compared to a boolean value.

if (someBoolean == true) // ew!
{
    ...
}
if (someBoolean) // omg, better!
{
    ...
}

It bothers me because it’s redundant. You already have a true or false, do you really need to compare it to true or false to know if it’s true or false?

I picked up this little bugbear back in the VB6 world. As I moved into the .Net realm, I was introduced to a new spin on booleans: Nullable<bool>. At it’s core, it’s still a boolean though, right? So my peeve lived on.

if (nullybool.HasValue && nullybool.Value == true) // blech!
{
    ...
}
if (nullybool.HasValue && nullybool.Value) // omg, yes!
{
    ...
}
if (nullybool.GetValueOrDefault()) // OMG, EVEN BETTER!
{
    ...
}

But alas, I have just learned that comparing nullable booleans to boolean values is actually quite nice. It saves you a lot of .HasValue-ing. I am officially ending my lifelong campaign against removing “== true” and “== false” from any and all code I come across; I’m making exceptions for nully-bools.

if (nullybool.GetValueOrDefault()) // gettin' paid per keystroke?
{
    ...
}
if (nullybool == true) // noice!
{
    ...
}

Now, all that said, there is still a place for HasValue. Sometimes you need to know if the value has actually been set, but I won’t want to see any more nullybool.HasValue && nullybool.Value-business. I’m done with that! (And a new peeve is born…!)

Advertisement

Author: Adam Prescott

I'm enthusiastic and passionate about creating intuitive, great-looking software. I strive to find the simplest solutions to complex problems, and I embrace agile principles and test-driven development.

3 thoughts on “nullybool == true”

Leave a comment

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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: