This article is part of a clean code in-depth course called Clean Code: Skyrocket Your Programming Career in 7 Days you can check it out. It’s curre

How to make your code reads like a poem? Beautiful boolean variables

submited by
Style Pass
2021-06-13 20:00:07

This article is part of a clean code in-depth course called Clean Code: Skyrocket Your Programming Career in 7 Days you can check it out. It’s currently available at an 87% off discount.

Since you are often using them in if statements you have a chance to make the code reads really really well OR make the code look really crappy and hard to read. Let’s see an example:

You are seeing this code for the first time, do you understand it? Or do you need some time thinking about it? I’m sure that you will figure it out eventually, but you need time. Now let’s extract the booleans and give them names. Let’s see if this will make the code read well:

Now imagine seeing this code for the first time. Let’s read the if statement. If person is hungry and person can afford dinner and it’s weekday — then make an order. I think that’s way better, don’t you think? But I still don’t like it. See, the first two booleans are working with the Person object. This logic can be encapsulated inside the object. Also, we can create an object for the weekday logic:

Now we have a Person class with the boolean methods in it. And we have a TimeOperations class that has an isWeekday method. Now let’s see the if statement. It’s one line of readable code. If you see that for the first time you won’t have a problem understanding what’s going on. This is because we hide the details inside named blocks of code. You should do this not only with booleans, but with all the code you are writing.

Leave a Comment