Sujet : Re: “Booleans Considered Harmful”
De : Keith.S.Thompson+u (at) *nospam* gmail.com (Keith Thompson)
Groupes : comp.programmingDate : 22. May 2025, 20:27:16
Autres entêtes
Organisation : None to speak of
Message-ID : <87frgwxx7v.fsf@nosuchdomain.example.com>
References : 1
User-Agent : Gnus/5.13 (Gnus v5.13)
Lawrence D'Oliveiro <
ldo@nz.invalid> writes:
I think most of this article is a load of nonsense, myself.
>
<https://www.infoworld.com/article/3990923/booleans-considered-harmful.html>
>
Thoughts?
It's not *all* nonsense.
1. Stay positive
2. Put positive first
Ok, sure. UserIsAuthorized is clearer than !UserIsNotAuthorized.
3. No complex expressions
Meh. The example he gives is:
if (user.age > 18 && user.isActive && !user.isBanned && user.subscriptionLevel >= 2) {
grantAccess();
}
I don't find that particularly problematic. His suggestion to replace
each subexpression with a named constant isn't horrible, and it can be
useful in some cases, but it can also add clutter.
Note that the first three points are advice about how to use Booleans
clearly, not about avoiding them. I guess a "Foo considered harmful"
title was too tempting.
4. Say no to Boolean parameters
This is perhaps his most valid point. I agree that
saveUser(user, true, false);
is too obscure. But for languages that support them, named parameter
associations neatly solve the problem:
saveUser(user, sendEmail = true, verified = false);
Unfortunately, a lot of very popular languages don't have this feature.
Comments are an alternative, but not a good one; it's too easy for them
to get out of sync with the code.
5. Booleans are a trap for future complexity
*Anything* could be a trap for future complexity. The example is
a Boolean "isSmallDrink", which needs to be changed when the boss
announces we're going to be serving small, medium, and large drinks.
I agree that a 2-element emum (small, large) would have been clearer
and more extensible. But refactoring is a thing, and revisiting
an earlier decision (changing the type of a variable) is something
that has to be done all the time.
-- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.comvoid Void(void) { Void(); } /* The recursive call of the void */