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…!)
Mind Blown! How did we not know this? I smell a re-factor in my future š
Lol, right!?
Reblogged this on Chris Hendricks… and commented:
Nice post from Adam Prescott, I am definitely going to start doing this.