1. Carry checkbox up to your high-level code
Every application is a sort of data processing. As such, in order to provide output, it requires some input. More often than not it’s a so-called “user input” and among user interfaces there happen to be checkboxes.
A checkbox indicate that some option is enabled or disabled and, as such, is a valuable way of controlling application flow. But a developer’s job is to put code into layers and split the ugly low-level code from the pure object-oriented (or functional) high-level code.
Unfortunately, we often fail and as we receive the checkbox value in a form of isPremium, isValid or isAuthorized, we tend to pass this argument deep into the application.
It should never be like this, because the more objects or functions know about isPremium or similar, the more conditional statements will appear to handle this information.
And the solution is to convert the raw input data as soon as possible into a high-level domain code with objects, higher-order functions and so on.
2. Use boolean to indicate objects interaction
Dealing with object-to-object interactions within a video game is an incredibly difficult process. So we have a character which is able co crunch when there’s not enough space to walk. How would you introduce such a feature?
Do you think that the character can check for isSomethingAbove and depending on that flag switch to crunching? Of course not, the character should be responsible for its actions, there should be some communication between character and its environment!
Such a model appears mostly when the developer does not expect much behavior from some minor thing. Here for example we may have a low ceiling that makes our character crunch. As the sole responsibility of the ceiling is to change the way the character moves, one may avoid to introduce a separate entity for it. But it's wrong! Even a single behavior is enough to delegate this responsibility for a separate entity!
3. Expose boolean in an API
Let’s assume you have a code where you need to compare two objects by their nature. For example, your application deals with door-to-door deliveries, you have to compare addresses for equality and expose areEqual to some sort of API.
Looks good, but remember that a boolean can only provide true or false! So there comes a business request to change the conditions for equality, but you still can expose only true or false. Can you see the problem?
The problem is that as you have exposed a boolean you cannot tell everyone that it is no longer valid! Maybe someone depends on it and will never know that a "new false" is a different "false".
If you need to expose raw data in such a form, always use some sort of nullable or enum to make sure you can easily make the field obsolete to tell everyone they can no longer count on it as they did before.
Top comments (0)