Live data from Hacker News

Don't use booleans (2019)

luu.io

11–20 of 152 posts

Re: Don't use booleans (2019)

#12

You can think of booleans as a built-in, two-value enum that has a common semantic meaning. Use booleans if this is suitable for your purpose; it will be suitable for many. That said... this article feels like a bit of a strawman. Does anyone by default use three booleans in cases that are arechetypical enums?

Unfortunately, yes

Re: Don't use booleans (2019)

#14
post #5

Solution in C#: use named parameters: RaiseInvoice(taxInvoice: false, sendEmail: true)

Which is far more realistic than defining single-use enums all over the place.

I don't know why more languages don't have named parameters...

Re: Don't use booleans (2019)

#16

Tangential but coding in JS/TS, I often will go for object arguments to make things more readable. If you have a function like: foo(arg1: boolean, arg2: boolean, arg3: boolean) Then when you call it it will look like foo(true, false, true) which is not great for readability. Instead I move all the arguments into an object which makes each field explicit. Ie. foo({ arg1: true, arg2: false, arg3: true }) This also carr…

Big time.

Re: Don't use booleans (2019)

#17
fetch( accountId, true, // include disabled, true, // fetch history, true, // fetch details );

typescript saves the day again

fetch(accountId: AccountId, options: {includeDisabled?: boolean, history?: boolean, details?: boolean})

Re: Don't use booleans (2019)

#19

I'm definitely a fan of making bad data 'unrepresentable' through the type system. The bit flag enum pattern is not so familiar to me in Python, but I recognize it from the CPython internals so maybe it's more common in systems languages. Not sure how I feel about explicitly listing every valid combination of flags, but I'm sure in some cases that's the right move.

Yes, 100%. Although you end up with some super gnarly types sometimes, so much better than marking a bunch of properties as optional but not handling certain combinations of them being passed in correctly.

Lord knows I still do that most of the time though...

Re: Don't use booleans (2019)

#20
post #5

Solution in C#: use named parameters: RaiseInvoice(taxInvoice: false, sendEmail: true)

That doesn't fix readability (is the invoice being raised not a tax invoice? Or are we not taxing the invoice being raised?).

That doesn't fix the possibility of adding a third possibility either (what if we separate non-tax invoices into two types of invoices?).

RaiseInvoice(InvoiceType::Tax, Notifications::Email);

Post reply on HN