5 ms·
One corollary about using positive space is that you realize we overuse booleans a lot. I routinely use a lot of boolean logic in my JavaScript and TypeScript c
by hardwaregeek 6y ago
One corollary about using positive space is that you realize we overuse booleans a lot. I routinely use a lot of boolean logic in my JavaScript and TypeScript code. I use it to decide when to display a component, when a component is being hovered, when it's odd, etc.
Recently I wrote a simple tree walk interpreter and had to implement boolean unary negation:
(UnaryOp::Not, Value::Bool(r)) => Ok(Value::Bool(!r)),
Why is this line important? Well it's quite possibly the first[^1] time I have used the boolean negation (!) operation in Rust!
Turns out, when you have proper enums, booleans aren't the best tool. Something like `isLoading` can now be `data LoadingState = Loading | Success`.
Why is that better? Well if you want to add a third or fourth state, it's trivial.
data LoadingState = Loading | Success | Failure
You can even give it data to pass along
data LoadingState a err = Loading | Success a | Failure err
Turns out you can have a lot more states than two. Often times in the equivalent boolean case you end up with a couple booleans: isLoading, isError, etc.
But then you end up with invalid boolean states! Like isLoading = true, isError = true. Huh? By making a multi-state type, you can restrict to only the possible states.
[^1]: Meh actually more like 5th but you get my point
- bigyikes 6y agoThanks for this! I'm going to refactor a PR I opened yesterday.
- nicoburns 6y agoI'm hoping that JavaScript adds rust-style enums at some point. Seems like it would be a perfect fit.
- valenterry 6y agoI fully agree. Not only is it easier to extend, it also makes reading the code so much easier and prevents mistakes, whereas for booleans you have to rely on variable names and hope to not pass them around wrongly.
- phibz 6y agoAlgebraic types are great. They let you encode portions of your logic in to the type system in a way that is readable and understandable.