I generally write code in C#. There are 2 mains ways that I have seen to check if a Boolean expression returns in the negative.
Using a bang to symbolize "Not" before the expression
!(expression)
And checking if the expression equals false
(expression) == false
I have gone back and forth between using both never really having a strong feeling as to which I prefer.
Today I have decided that I believe one is better than the other.
I came to this conclusion by really thinking about the Principle of least surprise. The principle when applied to coding is that you want your code to not surprise the next developer. What can you do to make your code easy to follow and understand?
Viewing these 2 options under the lens of the Principle of least surprise, I think one is clearly more surprising than the other. I think that using the bang before an expression is much more surprising than equating the expression to false. The little exclamation point can get lost while reading code, especially complex code.
Now I will use equals false going forward to make my code as unsurprising as I can.
Using a bang to symbolize "Not" before the expression
!(expression)
And checking if the expression equals false
(expression) == false
I have gone back and forth between using both never really having a strong feeling as to which I prefer.
Today I have decided that I believe one is better than the other.
I came to this conclusion by really thinking about the Principle of least surprise. The principle when applied to coding is that you want your code to not surprise the next developer. What can you do to make your code easy to follow and understand?
Viewing these 2 options under the lens of the Principle of least surprise, I think one is clearly more surprising than the other. I think that using the bang before an expression is much more surprising than equating the expression to false. The little exclamation point can get lost while reading code, especially complex code.
Now I will use equals false going forward to make my code as unsurprising as I can.
I actually prefer a third option which is. To replace the entire Boolean expression with a variable named "isSomething" then using ! or == false should be irrelevant to the person reading the code. Of course you could also argue that within you assignment to the "is" variable you should be using == false instead of !. Good post.
ReplyDeleteThank you for the feedback. I agree that is a good way to make this even clearer to the next developer, and as you mentioned I believe in many cases these would be used together.
Delete