Hacker News
How many options fit into a boolean?
gizmo686
|next
[-]
It is a specific optimization based on the idea of storing one type inside of another type by finding a "niche" of unused bit pattern(s) inside the second type.
It has far more useful application than a tower of Option 254 deep.
ralferoo
|next
|previous
[-]
Even now, I still find myself using true/false/null on occasions, but I'm usually smart enough to replace it with an enum at that point. The only time I don't is when it's an optional parameter to a function to override some default/existing value, at which point it then makes sense to keep it as an optional bool.
hinkley
|root
|parent
|next
[-]
gizmo686
|root
|parent
|previous
[-]
Aurornis
|root
|parent
|next
[-]
For more common situations where the yes/no bool is not available yet or should not be considered, constructs like Rust’s Option<bool> are a very good fit. Layering the bool inside of an Option creates intentional handling about the presence or lack of value first before you can work with it.
pavon
|next
|previous
[-]
gizmo686
|root
|parent
[-]
Option<NonZeroU32> seems like a much more reasonable to justify this with. Also, enums can easily have invalid bit patterns that are unused without there being any specific bit that is always available. All you need is a single variant of the enum to have a free bit, and you have a niche to shove None into.
nine_k
|next
|previous
[-]
shagie
|next
|previous
[-]
nitnelave
|root
|parent
[-]
shagie
|root
|parent
[-]
public static void main (String[] args) {
Optional<Boolean> n = Optional.ofNullable(null);
Optional<Boolean> e = Optional.empty();
System.out.println(n.equals(e));
}
true
https://ideone.com/EGRdi5A null in an Optional is empty. So you've got:
Optional<Boolean> n = null;
Optional<Boolean> e = Optional.empty();
Optional<Boolean> t = Optional.of(Boolean.TRUE);
Optional<Boolean> f = Optional.of(Boolean.FALSE);
priowise
|next
|previous
[-]
RobotToaster
|next
|previous
[-]
You can make them smaller using bitfields in C.
vadelfe
|next
|previous
[-]
mock-possum
|previous
[-]
Ah how many of those options fit into that boolean. Word games!