DEV Community

Discussion on: Boolean flags are sad little enums

Collapse
 
webbureaucrat profile image
webbureaucrat

I agree, and I would take it a step further--if you're passing flags, you should ask yourself if what you really need is a separate function. Like, consider:

jsonb_set_or_create(data, '{user, role}', {
  id: 'supervisor',
  title: 'Chat group supervisor',
})

jsonb_set_or_throw(data, '{user, role}', {
  id: 'supervisor',
  title: 'Chat group supervisor',
})
Enter fullscreen mode Exit fullscreen mode

There are times when passing flags or enums makes sense, but usually I think this is the better option because it results in less nesting inside the function (no switches or if/thens) and a little more intuitive to read the calling code (although readability is largely subjective).

Collapse
 
latobibor profile image
András Tóth

Fun fact this example was taken straight out of Postgres and indeed the flag is there, I did not make it up.
Your function names are very short and descriptive, I like them a lot! Thanks for your comment!

Collapse
 
hakanai profile image
Hakanai

I'd definitely go for a separate function. I'd reserve enums (or possibly better, strategy objects?) for the case where there is more than option and I don't want to explode the API to N×M functions.

Collapse
 
nricks profile image
nricks

The strategy pattern where your flags/enums are actual representations themselves of the behaviour you want to achieve is much nicer and cleaner from a declarative standpoint.

Always keeping in mind the common sense boundary of over engineering.

Thread Thread
 
webbureaucrat profile image
webbureaucrat

The problem with saying that enums are more declarative than separate function definitions is that that's really only true if you're thinking of functions as imperatives, but functions themselves are also values and can be used just as declaratively as enums, but using functions over enums better encapsulates meaning by tying the representation with the definition.

OO patterns like that are mostly an attempt to make imperative languages a little bit less imperative, but they aren't inherently better than just doing things in a functional way.

Thread Thread
 
nricks profile image
nricks

much sorry I was in a hurry I meant to type:
"where your flags/enums are functions and actual representations themselves of the behaviour"

:D