Improper uses of Booleans causes headaches for people who are reviewing your code. Lets take a look at some good, and not so good uses.
Don’t be negative
Looks simple and readable right? Wrong. It's one step away from being misused.
Not not logged in. Double negatives are a gotcha in language and coding and should be avoided. Fortunately the solution is an easy one. Remove the negative prefix (such as not, doNot, dont) from the variable name.
1 2 3
Is it really necessary to compare the variable to false? Imagine this conversation.
You are at Subway and they ask you 'Would you like your sandwich toasted?' Would you reply with 'Toasted equals false' Or 'Not Toasted'
Avoid comparing with a literal true or false. The correct way to express this is :-
A Boolean Flag?
$reportFlag is a little vague. In this case it is determining if an object is included in a report. So if $reportFlag is true, does that mean that the object is included or excluded? If you have to ask yourself the question then you have already failed and need to rethink what this variable should be called.
This is okay as long we are using the word ‘report’ as a verb. ‘If we report this then’ is how you would read this. Some people may not be able to make that leap so if you want to be more precise you could make it :-
So to sum up, these three things will go a long way to making your code readable.
- Remove the negative prefix (such as not, doNot, dont) from variable names.
- Avoid comparing with a literal true or false.
- Avoid vague terms like flag for Boolean values.
Consider these ideas when choosing
- Variable names
- Object properties
- Database field names
- Method or function parameter names
Is there something i’ve missed? A hole you could drive a double-decker bus through? Leave a comment below.