Sunday, April 5, 2015

Clean Code Practices : Conditions

 

It is said

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”

so that we have to make sure the code we write should be easily read and understood by the other developers. This post I will be discussing practices we can follow to make our conditional statements clean. In this post I will mention code dirty and clean to you to understand the difference

Principles:-

  1. Clear Intent
  2. Use the right tool
  3. Bite-size logic
  4. Sometimes code isn’t the answer

 

1.Use Positive Conditionals

When you write conditions always try to use positive conditionals rather using negative because humans are more comfortable in grabbing positive things.

Dirty
if (!isNotlogggedIn)
            {
            }

see above example it is bit confusing to understand the meaning in first time.

Clean
  1. if (logggedIn)
  2.             {
  3.             }

 

2.Use Ternary operator

see the following example first.

Dirty

  1. int bookingFee;
  2.  
  3.           if (isEarlyBirdBooking)
  4.           {
  5.               bookingFee = 5000;
  6.           }
  7.  
  8.           else
  9.           {
  10.               bookingFee = 8000;
  11.           }

we can see the variable “bookingfee” is referenced two places and this code has 11 lines of code. For this kind of conditions you can use the ternary operator to make the code cleaner.

Clean

  1. int bookingFee = isEarlyBirdBooking ? 5000 : 8000;

so that you can see, this has

  • less code
  • intention of the logic is short and clearly presented

3.Avoid using ‘Stringly’ types

see the following example first

Dirty

  1. if (user.Type= "Administrator")

in this sample we are checking a condiition against a string. Which might lead to many issues. There could be case mismatch, also developer might make spelling mistakes. To avoid these try to use enums rather using string values.

Clean

  1. if(user.UserType==UserType.Administrator)

if you use enums

  • there will be no typos
  • You will get the intellisense support from visual studio as it shows all possible values for user type
  • Also you can easily search where a specific user type is used in the code. Rather using enums if you use sting and then you search it will search commented code and all other unwanted stuff.