- When dealing with MySQL, I typically use the BOOLEAN type, which is equivalent to TINYINT(1), or 1/0
- In most languages I work with, true/false is preferred
- When displaying forms, sometimes "Yes / No" makes more sense
views:
1127answers:
7I use booleans for true/false fields in databases. Some people use ENUM('true', 'false')
, but thats not my preference. For programming languages, I always use true/false, even if setting it to 0 or 1 will work. And if the form requires 'yes'/'no', I still use booleans to represent the values, but display them as strings that are more logical.
Which is easier to read?
while(true) {}
while(yes) {}
while(1) {}
I'll stick with true for most cases.
true
and false
makes a lot more sense to me, in code - partly through familiarity, I'm sure. I suspect I'd get used to yes
and no
pretty quickly. 1 and 0 really doesn't work for me though.
Consider the expression
age == 5
It's a test for truth-hood. Is the value of age
5? Yes, it's true. Both "yes" and "no" would be fine for me, but the idea that the answer to the question "Is the value of age
5?" is "1" seems pretty counter-intuitive to me. Just because that's the typical binary representation of truth-hood doesn't mean it's a useful one at a higher abstraction.
Here are rules I live by...
Rule #1
Use well defined constants in the programming languages that you use to communicate with the CPU, i.e., true/false in most modern cases for boolean values. If a database offers a boolean type or some such equivalent, of course it should be used.
Rule #2
Interact with users of your software by using their preferred language and idiom, i.e., Yes/No questions should offer Yes/No (or perhaps an alternative to No, such as Cancel).
Rule #3
Uncertainty should be expressed in terms of scope, i.e., "that depends", which will be followed up by the question "on what?". I know developers who answer the question by copying and pasting just about every dependency they may need into every code file of a project as a 'using' statement. That's just sloppy, and please bother to alphabetize or at least group namespaces together.
When a bool Just Isn't Enough
Incidentally, an interesting twist to this, available in C#, is Nullable;
The you can write
Nullable<bool> RespondToIritatingQuestion()
{
return new Nullable<bool>();
}
OR
bool? RespondToIritatingQuestionWithSytle()
{
return new bool?();
}
and the questioner would need to evaluate your response before even knowing what the answer, if there is one, might be...
bool? answer = RespondToIritatingQuestionWithStyle();
if (answer.HasValue)
Trace.WriteLine("The bloke responded with " + answer.Value.ToString());
else
Trace.WriteLine("The bloke responded with 'depends'.");