Path: csiph.com!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.programming Subject: Re: =?utf-8?Q?=E2=80=9CBooleans?= Considered =?utf-8?Q?Harmful?= =?utf-8?Q?=E2=80=9D?= Date: Thu, 22 May 2025 12:27:16 -0700 Organization: None to speak of Lines: 60 Message-ID: <87frgwxx7v.fsf@nosuchdomain.example.com> References: <100mhh5$3b9hp$3@dont-email.me> MIME-Version: 1.0 Content-Type: text/plain Injection-Date: Thu, 22 May 2025 21:27:21 +0200 (CEST) Injection-Info: dont-email.me; posting-host="dae22f89fe428551773c9395a452d8f1"; logging-data="3816967"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX197jN7tO9KlyYq+ogGAM950" User-Agent: Gnus/5.13 (Gnus v5.13) Cancel-Lock: sha1:t4dbhgB2qE3p8D54IKi2EOFb3HE= sha1:88Agfcv2Rriw7PFv7ict0jc/pGo= Xref: csiph.com comp.programming:16779 Lawrence D'Oliveiro writes: > I think most of this article is a load of nonsense, myself. > > > > 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.com void Void(void) { Void(); } /* The recursive call of the void */