What is your preferred boolean pair: 1/0 Yes/No True/False?

99封情书 提交于 2019-12-03 21:19:20
enum Bool 
{ 
    True, 
    False, 
    FileNotFound 
};

http://thedailywtf.com/Articles/What_Is_Truth_0x3f_.aspx

In code: true/false.

In the UI: Yes/No or OK/Cancel

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.

Which is easier to read?

while(true) {}
while(yes) {}
while(1) {}

I'll stick with true for most cases.

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'.");

1 or 0 for SQL. SQL has a boolean type for a reason. Also, in very large databases, it can effect performance.

I 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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!