tags:

views:

1040

answers:

16

Why does boolean data type accept true or false values only, why cant it accept 0 for nothing (which is neither true nor false)?

+3  A: 

A boolean represents a single bit, which is either 0 (false) or 1 (true).

A NULL / zero value would only be possible for an object type, which boolean isn't (as it would basically defeat the purpose of the type in the context of boolean algebra).

If I remember correctly, Java does have a Boolean object type, which could conceivably be NULL. (Edit: And Rob's answer shows that C# also has such a beast, bool?.)

However, as I said, from the standpoint of boolean algebra a NULL value does not make any sense.

DevSolar
In all fairness, a single bit in a computer could be 0V (false), 5V (true), or not connected. This not-connected state is often called high-impedance (high-Z), and could be associated with a null value. While Boolean logic has no place for this, it's not unreasonable to ask why you can't also represent "I don't know"?
Gabe
@Gabe: The term "boolean" comes from George Boole, who invented Boolean Logic - which is the logic concerning elements that can contain *two possible values*. The third state "undefined" or "I don't know" has no business being stored in an "boolean" element. You couldn't do Boolean logic on it, you'd have to check for the condition before any operations. Hence, you could just as well store that information elsewhere - and indeed you should. The contract of "boolean" is "true | false". Having it store "undefined" as well is effectively a breach of contract. And bad design style to boot.
DevSolar
DevSolar: You're preaching to the choir, I think. I know it was invented by Boole, which is why I capitalized Boolean. I also said that Boolean logic has no place for null values. But I think it's a reasonable question to ask, and the answer would be "`bool` can only represent `true` or `false`; use `bool?` if you need an unknown state".
Gabe
@Gabe: ...and be aware that it's still a somewhat awkward construct that can not be represented in all languages.
DevSolar
+30  A: 

Because then it'd be a tri-state value, not a boolean.

If you're working in C# and trying to map bool to a nullable database column (which seems to be the usual cause of asking this question), then what you're after is Nullable<bool>, also represented as bool? which allows you to state that the value of the variable is true, false or null. For example:

bool? trueFalseOrUndefined = null;
bool? trueBool = true;
bool? falseBool = false;

To add to my answer, an example of a situation where this might be applicable would be where you have a database containing a table of Product's, each of which is a member of a discete Category (for example: Toys, Books, Chairs), and has a stored property IsCheapestInCategory which is calculated by a batch process once every hour. If a new record was inserted 2 minutes after the batch process was executed, it would be correct for IsCheapestInCategory to be NULL rather than true or false. Following on from that it would be sensible to represent this in your C# code as:

class Product
{
  public string Name  {get; set;}
  public string Category {get; set;}
  public bool? IsCheapestInCategory {get; set;}
}

However, it would be incorrect to use a bool? to represent something like 'Yes', 'No', 'Sometimes', as in this case an enumeration would make far more sense with the added advantage of being more understandable to anyone maintaining the code in the future.

Rob
*Cough*... `bool?` ? Remind me to think twice whether I really should pick C# as my next language of choice...
DevSolar
@DevSolar, and just how would you represent an undefined value for a boolean? Take an example of a database that stores products and has a boolean field for "IsCheapestInCategory" that's calculated as a batch process every hour. If a new product is added 2 minutes after the batch process runs, what value should be put in "IsCheapestInCategory"? I say null, because it's unknown. Following on from that, how would you represent that in your C# code? :-)
Rob
Using bool? (although perfectly legal) seems like a bad idea. In a situation where you don't know if the value is true or false (and null seems like a valid state), you should just implement another boolean value testing as to whether you know the value or not. It would almost be some type of sick joke: geek 1: "Is it true or false?" geek 2:"ehh... maybe"
MunkiPhD
@MunkiPhD, but it's not "maybe", it's "I don't know (yet)" :) If you add in another bool you then have even more fields to keep track of when one field could quite succinctly hold the full range of values to describe the property. Plus, you've introduced the opportunity for a possibly invalid state: A piece of code updates IsCheapestInCategory to `true` and forgets to set IsCheapestInCategoryIsUndefined from `true` to `false`, and bam, you've got invalid state.
Rob
bool? can often be a good way of representing a nullable bit field in a database. In a database this type of field tends to represent a boolean for which no data has been provided and a nullable bool is a good way to represent this in code. However it is a bad way to represent a true tri state value such as yes/no/maybe.
Ben Robinson
@MunkiPhD - this approach has been used many times by many people to successfully model boolean values that can be null. Are you just trolling or do you understand the .NET generics / Nullable<T>?
RQDQ
How do you indicate FileNotFound? http://thedailywtf.com/Articles/What_Is_Truth_0x3f_.aspx
dkackman
@ Rob: Before you ask how I would *represent* an undefined value for a boolean, ask yourself how you would *interpret* such a value. Your `IsCheapestInCategory` example is very, very broken: Either `IsCheapestInCategory` is calculated on every product stored (or on each retrieval of the value, depending on what is more seldom), or the information contained is bogus anyway (because it's most likely outdated). If I use a boolean, I want a bit to store 'true' or 'false'. If I need a third state, I chose an integer, an enumeration or whatever, but a boolean would just be the wrong design choice.
DevSolar
@DevSolar, I think we'll have to agree to disagree, as IMO, having an undefined boolean is simple, clear and quite obvious. IsCheapestCategory was a contrived example, but there are plenty of others. Storing something that is *ordinarily* a boolean value, but may sometimes simply **not be known** as an integer (or an enumeration for that matter) is lunacy. That said, that's my opinion and yours clearly differs. :)
Rob
@MunkiPhD: a nullable bool *is* two bools. As you suggest, one bool tells you the non-null value, and the other bool tells you whether the whole thing is null or not. There's nothing magic about bool? that you couldn't do yourself with two bools; it just packages up those two bools in a convenient struct that the compiler knows how to do lifted logic on.
Eric Lippert
@Eric - I'd say that `bool?`'s boxing behavior is fairly magical, though perhaps irrelevant to the topic at hand.
kvb
@kvb, isn't there that saying that goes something along the lines of "any technology, sufficiently advanced, is indistinguishable from magic"? ;=)
Rob
@kvb: good point.
Eric Lippert
I understand how nullable types work and what not, but the best way to sum it up is "it depends" on the context in which you decide to have a True/False/DontKnowYet state. In a database context, having a null state MAKES sense, but in my opinion it seems rather broken when you get to your code. When you get to the point where you need three states, you most likely have something more complicated than true/false and its likely-hood of changing is much higher. At that point, you're constantly going to be checking for nulls as opposed to state- who's meaning could be lost as you traverse layers.
MunkiPhD
+5  A: 

It only accepts two values because a proposition can only be true or false.

If you want a third, indeterminate state, then you need ternary logic.

Peter Alexander
+11  A: 

Because that is the nature of boolean, it is either true or false, like a bit can be only one or zero. What you are looking for is probably this: Ternary_logic

PeterK
+1  A: 

For that you want to use a nullable bool and set it to null to specifiy an undeterminate state.

w69rdy
+6  A: 

Boolean represents a logical value. These can only be represented as true or false.

What you are probably looking for is Boost's tribool in C++.

In C#, you can make any struct (built in types save for string are all structs) be able to take a null value by appending the nullable type declaration ?, ie. bool?.

bool? foo = null;

I'm sure there's a similar structure in Java, but I don't know Java, sorry.

Matthew Scharley
In java you could use the Boolean wrapper object, which can be true, false, or null. Though that may cause more trouble than it's worth.
Andrei Fierbinteanu
+3  A: 

Booleans are either true or false because computer logic is binary, not fuzzy.
As for the undefined value, there are objects wrapping booleans (ex java.lang.Boolean in java) which can be null.

ghaxx
+5  A: 

Because that's the definition of the boolean type?

George
+4  A: 

In Java, if you need something that can be true, false or "empty", use the Boolean wrapper class:

Boolean flag = null; // use null to indicate "empty"

flag = true; // will use autoboxing

if (flag == null) {
    System.out.println("Empty!");
}
Jesper
Just because you can does not mean you should. Bloch strongly advises against this anti-pattern.
FredOverflow
Yes, and `Boolean flag = null; if (!flag) System.out.println("Empty!");` will throw NPE, thanks to autounboxing
Rorick
Yes, autoboxing and -unboxing is in my opinion the worst 'feature' that was introduced in 1.5. I usually set my eclipse compiler warnings to level warning or error for autoboxing
seanizer
@Rorick - but that's the dilemma with every tristate type, even if a theoretial boolean type could hold false, true and 0 - the test ìf (flag)` would have to fail on the 'undefined' third state. `Boolean` is, btw, a good type for boolean values received from a database table where `NULL` is allowed.
Andreas_D
@Andreas_D: Don't agree. Of course, when we have inconsistent type with inconsistent operations we'll get inconsistent behaviour like those with `if`. Mentioned NPE is quite unclear and misleading. Generally, I don't expect any exceptions from Java control flow operators because they, well, don't throw exceptions. Methods throw them, but not operators. And here it looks as if `if` itself has thrown NPE. Say, in Groovy this case will be coerced to false, that is more consistent from my standpoint.
Rorick
@Andreas_D: And I don't see any obstacles preventing from designing consistent three-state boolean type in general. As for Java, all its "language extensions" were made on syntactic level on top of the same old bytecode which knows nothing about "undefined booleans". Hence, auto(un)boxing could hardly be consistent in principle and was doomed to some trade-off.
Rorick
+1  A: 

hey subanki, I wonder if you're also curious about why:

  • can't an int be nothing, why does it have to be "something", like 0, 2, or -2.

  • can't a datetime be null, why must it be a "default" value.

This is because, in languages like c# and Java, you have the notion of reference types, and value types.

bool is a value type, thus it must contain a value.

You could then get into philosophical debates as to why it must be a value type... and I imagine it's to keep the language, be it c# or Java, clean and consistance, to keep it logical, and strict, so it makes "sense".

Of course, as others have mentioned, c# at least has got a round that with the idea of a "nullable" type, which any type can be, and other languages have their ways.

There's an interesting article on types here:

http://creativekarma.com/ee.php/weblog/comments/value_types_in_java/

and here:

http://en.wikipedia.org/wiki/Value_type

andy
""You could then get into philosophical debates as to why it must be a value type... and I imagine it's to keep the language, be it c# or Java, clean and consistance, to keep it logical, and strict, so it makes "sense".""..................................................... pleae dont flame me when i clear my doubts
subanki
@andy - each rule has its exceptions: `double` is a value but it can be a `NaN` (Java at least)
Carlos Heuberger
+1  A: 

A valid Boolean may only have two values by definition or it world be no longer Boolean! A Boolean value is a mathematical entity, not just another integer type.

However, of the languages you tagged both C# and Java allow a bool object to have a null value indicating unassigned. You cannot perform operations on such an object without causing an exception. In C++ if you really must you could create a Bool class with sufficient operator overloads to make it do the same (at some probable great cost to efficiency, and limited actual utility). A partial example:

class Bool
{
    public:
       Bool() : null(true) {}
       Bool( bool b ) : state(b), null(false) {}

       // overloads for =, ==, !=, >, <, >=, <= etc.
       // which raise exception as necessary for null operands
       ...

    private :
       bool null ;
       bool state ;
} ;
Clifford
+6  A: 

They called it Boolean because they only wanted it to store either true or false. So there's actually no scope for anything else.

All discussions are heading towards proving why a Boolean type can only store true or false which is a wrong direction IMHO.

Imagine yourself in a shopping-mall where you're buying yourself a t-shirt and your size is XL. You came back home with a cool t-shirt of size XL. Now you're asking why it is an exact fit to only those with size XL. The answer is simple, because when you bought the t-shirt,you knew your size XL and you wanted to buy the t-shirt of your size that is XL!

this. __curious_geek
A: 

For a start, in C++ (and C and Objective-C), 0 is false and anything else is true. false is also a bool that happens to be 0 when cast to int, and true is a bool that happens to be 1 when cast to int.

What exactly, do you mean by "neither true nor false"?

  • Maybe implies a probability ("Will I win the lottery?")
  • Sort of implies some sort of "fuzzy logic" ("Am I tall?")
  • Unknown implies something that hasn't been calculated yet ("Is it raining?")
  • Don't care implies a lack of preference ("W
  • Mu implies incorrect assumptions in the question ("Have you stopped beating your wife yet?")

Don't forget the traditional 4-state logic (01ZX) or IEEE 1164 9-state logic...

tc.
+2  A: 

I agree with most of the responses that a boolean should be true or false only. However, I have had scenarios where a database boolean column type allowed null values and null had meaning to the application (not how I would have designed or implemented it but I still had to handle it).

From the Java point of view:

boolean b; // primitive type - can be true or false
Boolean b2 // reference variable - can be true, false or null

Although b2 could cause NullPointers e.g.

if(b2) {} // can cause a NullPointerException if b2 is null

You could also create a pseudo-boolean datatype using enums e.g.

class Processor {

    enum TernaryBoolean {
        TRUE,
        FALSE,
        UNKNOWN
    }

    void checkSomething(TernaryBoolean flag) {

        if(flag.equals(TernaryBoolean.UNKNOWN)) {
            // stuff
        } else if(flag.equals(TernaryBoolean.TRUE)) {
            // other stuff
        } else {
            // other stuff again
        }
    }
}

I used the enum solution as it meant I didn't have to check for nulls everytime I was writing an if statement (although, in reality, all I was really doing was replacing the null check with the UNKNOWN check).

dairemac
+2  A: 

Ahh, what does it all mean? Perhaps a boolean should have real and imaginary parts - after all the answers to many questions can be complex (groan!).

pgast
A: 

SQL logic is all tri-state: true, false, or null which is interpreted as "unknown". In SQL truth tables:

X     Y     X AND Y  X OR Y
true  true  true     true
true  false false    true
true  null  null     true
false true  false    true
false false false    false
false null  false    null
null  true  null     true
null  false false    null
null  null  null     null

As others have noted, Java Boolean can be TRUE, FALSE, or null. But you can't perform logical operations on null values, you'll throw null pointer exceptions. You have to test for them by hand.

(I don't know about C#'s "bool?". I admit I didn't know that existed until today.)

If you need to handle tri-state logic like that, or if you have some other pseudo-boolean requirement for "true", "false", "maybe", and "ask Bob" or whatever, you should just create your own object that supports the values you need.

Jay