Making Your Conditionals Better

A recent stackoverflow.com post has lead me to this blog.   In the post someone was asking if a particular block of code was functional equivalent, and inadvertently started a holy war.  Just two quick readability tips.

Do your best to implement “postive” conditional if/else blocks.

Translation don’t negate your conditionals.

Example:


if(!value){
   Console.WriteLine("Logic");
}else{
   Console.WriteLine("Else Logic");
}

It is much more readable if you switch them:

 if(value){
   Console.WriteLine("Opposite Logic");
  }else{
   Console.WriteLine("Else");
  }

It is also a lot easier to add more conditionals into the chain if it is not negated.

Use brackets!
This is a simple one. I know sometimes they take up extra space, but I have seen countless bugs that stem from this:

   if(lazy)
     foreach(string x in listOfStrings)
        Console.WriteLine("Will only ever do this for logic!" + x);

So what happens is someone, that has no clue how to read your code and probably has no real clue what your code is doing, gets assigned a bug and some how tracks it down to that statement. The bug that we need the ability to trace the size of string. So he changes it:

  if(lazy)
      System.Diagnostic.Trace.WriteLine("Size: " + listOfStrings);
     foreach(string x in listOfStrings)
        Console.WriteLine("Will only ever do this for logic!" + x);

And now he has managed to introduce another bug. I know this is a simple case, but it illustrates the need to be a pessimistic programmer. You never know who will be reading or maintaining your code so do your best to limit a users ability to do something stupid.

In case you need it the correct solution would be to use braces around the if AND for:

   if(lazy){
     System.Diagnostic.Trace.WriteLine("Size: " + listOfStrings);
     foreach(string x in listOfStrings){
        Console.WriteLine("Will only ever do this for logic!" + x);
     }
   }
Advertisements
Tagged with:
Posted in C#, Programming

Leave a Reply

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: