An Interest In:
Web News this Week
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
- April 13, 2024
- April 12, 2024
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
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To