Writing Cleaner Code 2 – Making Cleaner if Statements and Boolean Expressions
Mid section of woman standing with spray bottle and napkin in kitchen at home

Writing Cleaner Code 2 – Making Cleaner if Statements and Boolean Expressions

This is part two of a series on writing clean code. This post is much shorter and touches on more technical and specific aspects. It’s centered on Java and C#.

 

Last fortnight, we looked at the concepts of clean code, and how practicing clean programming saves you and everyone else who bumps into your code worlds and worlds of frustration and time.

As I revealed to you last time, programmers don’t program 24/7 as many people may think, and it turns out they do lots of other activities seldom thought about.

They have to live down the pain of long board meetings, discuss systems, meet clients (okay, that’s usually the lead developer’s job) and lots of overhead activities.

And more importantly, a lot of time will be spent reading either by meticulously search through older pieces of software for bugs, reading through open-source projects to integrate them into their own software, or reading through old code to understand and update them.

We tacked all that rather viciously last post, so today I’m going to talk about something much more specific: if statements and boolean expressions.

 

A Typical Day in Kansas

Now I’m pretty sure each and every one of you know how to define a typical if statement, so let’s get straight to it.

So let’s say we had 3 variables, and we wanted them to interact with each other to determine whether a game player should be notified whether he’s gonna die soon or not:

boolean isHurt;
String playerStatus;
int health = 100;

Okay, so let’s get some typical code to see how this would work.

if (health < 5){
    isHurt = true;
}else{
    isHurt = false;
}
       
// Rest of your game's the code goes here
      
if(isHurt){
    playerStatus = "You're badly hurt!";
}else{
    playerStatus = "You're cool dude";
}

That seems pretty functional, right? It’s readable, and it follows the principles of clean code. However, this code was clearly written by an amateur. Let’s look into why:

 

Free from Curly Braces!

As you know, Java and C# use braces a lot. Along with the pesky semicolon, they are what tell the compiler when one thing ends and another thing begins. However, sometimes we overuse them. The code above is a primary example, actually.

Compilers aren’t stupid (well…that’s relative, considering that they don’t know that 1 and 1.0 are the same thing), and sometimes they can infer when something ends without the use of a brace.

The number one example? The if statement.

If you have an if statement with only one line of code in the decision, you can (and will be liked more by the programming gods if you do) remove the curly braces. So that means that our code would become like this:

if (health < 5) isHurt = true;
else isHurt = false;

//The rest of your game's code goes here

if(isHurt) playerStatus = "You're badly hurt!";
else playerStatus = "You're cool dude";

We could decide to do something like this too:

if (health < 5)
    isHurt = true;
else
    isHurt = false;

(I gotta admit, this is looking a bit like Python  right now).

But this second style has a drawback. If you’re reviewing your code in a hurry and decide to add something to one of these decision areas (because you forgot that braces are needed if more than 1 operation is in a decision area), you’re gonna get a nasty error in there (which may end up being a pain to find later on).

It’s perfectly legitimate to leave like this though, but I usually play it safe and leave it in the one-line format. However, that’s not the only way to clean up this code.

 

Short and Simple

Guys, take a look at the first if-else statement. Notice anything fishy in there?

No? Are ya sure?

It’s doing the same thing twice!

If statements take boolean values as their conditions. That’s why typing out if(true) doStuff();would compile with no errors (even though it’s a pretty dumb piece of code, since there’s no real reason to ever use a if(true) statement). The if statement retrieved a condition that was true, so it performs the doStuff() method. However, if the condition in the if statement is a boolean value, why don’t we just assign it to the isHurt variable directly? That’s actually how boolean statements should be assigned sometimes. So our code would now look like this:

isHurt = health < 5;

//The rest of you game's logic goes here     

if(isHurt) playerStatus = "You're badly hurt!";
else playerStatus = "You're cool dude";

Our code is still functionality intact, but there’s still one more thing we can do to make this code flawless.

 

The Mysterious ?: Clause

Now in actual fact, this clause isn’t so mysterious or arcane. I just call it so because I first used it a whole 18 months and 3 applications after I started programming, yet it’s really simple and useful.

So, I find it interesting how I never used it until then.

These clauses can be used in variable declarations; they’re the product of a variable declaration mixed with an if statement. It’s present in both Java and C#.

Anyhoo, this is a the formula for a ?: clause :

 

Variable = (condition) ? (value of true) : (value if false)

 

I like to think if it like a question. So it’d be like “is the condition true?” Notice how I’ve made the question mark bold. “If yes, do that. Otherwise: Do this”.

So for the code we have, we could make the second if statement like this:

playerStatus = (isHurt) ? "You're badly hurt!" : "You're cool dude"

And BAM!

isHurt = health < 5;

//The rest of you game's logic goes here

playerStatus = (isHurt) ? "You're badly hurt!" : "You're cool dude”;

With a little clever thinking, we’ve changed that 11 line behemoth into a 3 like beauty.

 

Throwing in the Towel

That’s it for today. I just wanted to share a bit of knowledge as to how to make these aspects of programming cleaner, because the truth is, they are one of the backbones of programming – you gotta get them right.

If you’re curious, I have a few links for you to look at. They’re about the ability to name loops in Java (I didn’t know you could do that either!) and the goto keyword in C#.

Goto statements link 1

Goto Statements link 2

Labeled Loops 1

Labeled loops 2

Till next time!

 

Photo credit: Freepik.com

Anderson

The owner of the Loading Developer blog and the Lumberjack Apps studio.

Leave a Reply