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:-
- Clear Intent
- Use the right tool
- Bite-size logic
- 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
{
}
see above example it is bit confusing to understand the meaning in first time.
Clean
- if (logggedIn)
- {
- }
2.Use Ternary operator
see the following example first.
Dirty
- int bookingFee;
- if (isEarlyBirdBooking)
- {
- bookingFee = 5000;
- }
- else
- {
- bookingFee = 8000;
- }
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
- 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
- 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
- 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.
Comments
Post a Comment