Semantics matter
2 min read

Semantics matter

Semantics matter

One of the advantages of being a software developer is you can enjoy programming humor. But things are not always as they seem. Case in point, this popular screenshot posted on /r/programminghumor

One of my senior wrote same single statement in if and else block.
I asked the reason, she replied, "this statement needs to get executed in both the cases."
Bravo.
She is my tech lead now.

As a tech lead myself, who often does things like that, I felt personally attacked (0k, not really, but it's more dramatic to say that). Now, without context, it's hard to say if the person in case is actually wise or just a dumbass but the truth is the approach described is very nuanced and it's something junior developers often miss.

There is more to code then performance or achieving a result. True, those thing matter a lot but the code also needs to have or convey a meaning. A junior developer might write: doSomething() and pat himself on the back. The app runs, all is well. Another developer sees the code and what does he take from it? That it should doSomething(). But let's take a look at the scenario described:

if (condition) {
   doSomething();
} else {
    doSomething();
}

To me, that read differently. What I'm getting from that is there are two business scenarios and in both situations we are doing the same thing. I'm also seeing a condition that might impact the code. I not only know the doSomething() part but I'm also getting a glimpse at the business requirements that created the need for the code.

Another personal pattern that I'm fond of and use it quite often is to use two different approaches.

The first one is this:

if (condition) {
   return true;
} else {
    return false;
}

And the second one is this:

if (condition) {
   return true;
}

return false;

They do the same thing but they have different meanings.

In the first pattern, what I'm saying in code is that there are two cases, one where the result is true and another where it's false.

In the second, what I'm saying is the result is false but there is one exception where it's true.

Both snippets of code evaluate identically and might even be compiled identically. But the meaning behind them is different and they describe different use cases.

Something to keep in mind before judging other people's code.