2 ms·
This applies to function parameters and return values: you almost never want to use a bool. Instead you want to use an enum with two values. Booleans are hard t
by cletus 5y ago
This applies to function parameters and return values: you almost never want to use a bool. Instead you want to use an enum with two values. Booleans are hard to read in most cases. Obviously there are trivial cases where this isn't the case (eg bool isDigit(char) is completely fine).
Contrived example:
bool connectToHost(string hostname, bool useSsl);
First problem: if it fails, why does it fail? Some will be tempted to throw an exception. Better is to return some kind of status.
Second problem: you add another version of SSL, now what? If you'd used an enum, it's just another value. If not, you now need to retrofit it.
Better version:
absl::Status connect(string hostname, EncryptionType encType);
People will often make mistakes when a function has 3 or more booleans and put the wrong value in the wrong parameter. With strongly typed arguments, this becomes a compiler error.
People will extend booleans to add a third value. In Java, for example:
Optional<Boolean> foo
But it doesn't end there. As I like to say, for when three values for your boolean just aren't enough:
@nullable Optional<Boolean> foo
Just start with enums.
- Psychlist 5y ago> People will often make mistakes when a function has 3 or more ... of anything. This is why non-compatible numeric subtypes are so valuable. Code like "quantity_sold = price" should not compile. You can do the same thing for other types using the same template but IME that's somewhat less common (but does happen: user_name = address!!). It would be nice to get a variation on std::pair that works in a similar way to Rust's std::result<value, error>, because std::optional is just a dressed up boolean. I did just swipe the std::pair declaration and do that, but having it official would be nice. Especially for the non-throwing version of the standard libraries.
- dragonwriter 5y ago> People will often make mistakes when a function has 3 or more booleans A function with three or more positional parameters in a language that isn’t badly broken (that is, one that supports keyword and/or structured parameters, which pretty much all significant languages do) is, IMO, a code smell. Even if more specific typing and IDE pulling up signatures can makes it less likely to make usage errors, readability is impaired.
- BenFrantzDale 5y agoI’m a big fan of `enum class IsFoo : bool { no, yes };`. I find it to be a great balance between type safety and conciseness. If you want your own unique Boolean-like type, that one line is all you need (unless you want operators, etc.)