Unnecessary Conditional Checks
Today, I want to underline some points about misused or over engineered conditional statements.
This image makes me smile everytime I see, and is a very good fit for our topic :)
So what do I mean about misused or over engineered conditional statement. I guess, some of these examples may bring up discussions, please comment with your rejections or approvals. I am always open for critics and learn from anyone.
Let me underline that the concepts I discuss is more applicaple if you are using ECMAScript5 and above.
Let’s take some samples from my code reviews at NodeJS;
This is a very common check and just to be on the safe side, we may use such a conditional statement. What do I mean by safe side is;
We are using and pushing for strict mode and undefined check is generally irrelivant. You can define strict mode as below;
This mode already gives and error if you assign a value to a variable which is not defined. So you need to define the variable as “var variable;”
Generally you only need to write a simple check as below;
Consider the below inline condition;
At first look this is ok for many programming languages. C# even has a special operator ?? just for this purpose. So that you can write in C#;
Good ha :)
Another tip for Conditional (ternary) Operator is, you can do more than one operation in a condition block like below. However, by means of readability of your code, do it if you realy need it ;)
Again another end for another post. Thanks for reading and if you found this post useful, please share it. I appreciate all types of feedback and encouragement.