Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
September 6, 2022 09:56 am GMT

Boolean flags are sad little enums

I was thinking today that when I was a mid experience level engineer I have found a couple of problems where I could finally do something very smart and use 3-state logic instead of the classic true-false one.

I jumped in excitedly only to lose it when I realized "Wait, doesn't this make instead a good enum?". And then I went with a good ol' enum and all was well.

And now I am thinking again: wouldn't it make sense to replace as much as boolean flags with enums instead (or at least used named parameters).

See this example:

jsonb_set(data, '{user, role}', {  id: 'supervisor',  title: 'Chat group supervisor',}, false);

When you are writing this, you still remember what was the false for the last parameter.
I give you a weak and if you are not using this jsonb_set function frequently you will have no memory of it.

We then waste time on things that could have been very clear.

Option 1: use enum

enum JsonbSetOption {  CreateIfDoesNotExist,  ThrowErrorIfDoesNotExist}jsonb_set(data, '{user, role}', {  id: 'supervisor',  title: 'Chat group supervisor',}, JsonbSetOption.ThrowErrorIfDoesNotExist);

Basically anybody will know what this will do.

Option 2: passing named parameters

jsonb_set(data, '{user, role}', {  id: 'supervisor',  title: 'Chat group supervisor',}, { throwErrorIfDoesNotExist: true });

Option 3: split it into two functions

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

It is up to you whichever you choose. Please don't just use random flags or else...

receiveSalary(you, false, true, true, false, null);

Original Link: https://dev.to/latobibor/boolean-flags-are-sad-little-enums-1h94

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To