This post may seem like sub optimization to some, however high readability of code makes code easier to understand and thereby change. In my opinion, great code is code that you do not have to spent much effort to understand - in other words the code is simple.
This post focuses on the readability for booleans and conditions. It is widely known that booleans should be named in a way that they pose a question and have descriptive names. Something else that I find important is to use positive names anywhere possible. I use the example of feature toggles in this post, as those are often harder to refactor later, than simple variables that just reside in code. I have sometimes seen - and probably written - feature toggles with names like the following:
if (disableNewFeature){
//do not do something
}
When the above boolean is true something is disabled. In my head I need to think an extra time when looking at the above, as I have to turn it around in my head. It is even harder to read the reverse:
if (!disableNewFeature){
//do something
}
The above basically reads as "if the new feature is not disabled do the following". Which again, I need to turn around in my head to read. It is often much easier to read positive names, like the below:
if (enableNewFeature){
//do something
}
The above is much more clear than the previous example and straight forward, and it is also much easier to read the opposite:
if (!enableNewFeature){
//do not do something
}
It easily reads as: "If the feature is not enabled, do not do something".
My examples can be replaced by many other boolean names such as isActive
or isConnected
, it works the same. I hope the above demonstrates that positive boolean names are easier to read, if you think differently or disagree please let me know in the comments!