📣 Announcement
If you want to get better at writing code, I have a Clean Code workshop coming up.
Reply to this email if you are interested and I will send the details.
Howdy,
The other day I was doing a code review, which made me double-take.
Now what is a double-take?
a delayed reaction to something unexpected, immediately after one's first reaction.
To put it better, you are driving a car and you see a girl walking through the corner of your eye. A split-second later, your brain found something exciting and you looked again. And that’s a double-take.
As you see, double-take can be risky as you can have an accident if you are not careful.
In code as well, doing a double-take means something is not right.
Here it was a code that looked something like this:
doSomething(x, y, true)
Can you guess why I did double-take?
Yes, it was the boolean passed in the argument of the function.
I could not understand why for the life of it, true
was passed in the argument.
I went back and started going through the code again to find the reason.
Boolean in function argument makes the code unintuitive
This is one of the major reasons why you should avoid passing a boolean as an argument of a function.
One way to solve the problem is to create two methods - one for each value of the boolean.
What that does is, it makes code easier to understand as then you have removed the ambiguity.
Caveat
Passing a boolean is not always evil. For example, you could be setting the value of a switch. In this scenario, it is fine to pass it as an argument.
isLightOn.set(true)
In Java, autoboxing of Boolean can cause a code smell
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. So a boolean will be converted to Boolean.
Do you know why this could be a problem?
The boolean can only have two states. true
or false
.
But a Boolean could have a possible of 3 states - true
, false
and null.
So when you are using a value of Boolean:
Boolean isLightOn;
if (isLightOn) { // Code Logic }
If you are not careful, isLightOn
can be null. What that means is, as a developer you need to keep this in your working memory. If you miss it, you have a bug right there.
Now that is an invariant.
It is something that you know that cannot be null but the compiler doesn’t.
A better approach would be something like this:
if (Boolean.TRUE.equals(isLightOn)) {
// Code Logic
}
📣 Shoutouts of the week
Coding in the Debugger: How to use in-situ coding in Java using Eclipse
Working at a Startup vs in Big Tech: A detailed comparison between working in startup and big tech
Protect Your Time: Something we forget in the humdrum of developer life.