I’ve read a lot of code over the years and I enjoy reading (and contributing to) open source projects. I’ve also read a number of example applications from online learning resources and unfortunately I believe this is where people, who don’t know any better, learn from and learn bad habits.

Recently I was watching a course on Pluralsight. Don’t get me wrong the course was great and informative however one of the lines of example code jumped out at me …

if (String.IsNullOrWhiteSpace(username) == false)

This in itself isn’t fundamentally wrong, however it’s not as clear as you’d expect a professional developer to write. If it appeared in a code review I was reviewing it would not pass.

Why would it not pass code review? A couple of reasons …

  1. String.IsNullOrWhiteSpace returns a boolean value, why the need to compare it again?
  2. Having a condition compare a return from another method to false can lead to miss understanding in less experienced developers
  3. Reading from left to right, as we do as developers, you initially think you want it to be empty and then just at the end it’s “erm, no”
  4. if(!string.IsNullOrWhitespace(value)) is clearer in what the intent of the code is doing.

The above is along the similar lines of …

if (myBoolValue)
{
	return true;
}
return false;

It’s explicit and technically not wrong, but it shows inexperience. It can also be a potential miss understanding of the condition being evaluated. What happens if another developer then randomly adds some code to the if body by accident? It will work for their new functionality or fix, but could have potential and subtle knock on impact which may not be picked up in testing (yes, the unit tests should cover this, but I live in the real world and this isn’t always the case!).

return myBoolValue;

Reads a lot clearer to me; is clean, precise and the intent isn’t ambiguous. The end game of a majority of code after all is adding functionality but allowing for maintainability which means clean and readable code. Don’t over complicate code but K.I.S.S!

I’d be interested in hearing your thoughts. Please contact me on Twitter @WestDiscGolf