How Would You Write This Conditional Branch?

This article was automatically translated from Japanese by AI. Read the original Japanese version →

1. Today's Problem

Have you ever hesitated over how to write a tricky conditional branch?
Here is a branching problem for you to try writing. It's simple, yet a little awkward.
f:id:kazasiki:20130615100507j:plain
I drew it in two or three minutes so it's a bit messy—please forgive me (^_^;)

To explain it in words, we branch based on the value of the variable flag.
If flag is 1, we run judge(), and if the result is true, we execute doSomething().
If flag is 2, we don't run judge() and just execute doSomething().
If flag is anything else, we do nothing.
Simple logic.

2. Let's Actually Write It

Now, before reading any further, try writing out this logic as code yourself.
You can jot it down on the back of a flyer with a pen or type it into a text editor.
Easy, right? Shouldn't take more than a minute.
Wrote it down?
Actually wrote it?
Once you've written yours, keep reading below.

3. Checking the Answers

So, how did yours turn out?

Here are a few answer patterns I put together.

private void hoge(int flag) {
    // flag = 1 or 2 or 3

    // Pattern1
    if (flag == 1) {
        if (judge()) {
            doSomething();
        }
    } else if (flag == 2) {
        doSomething();
    }

    // Pattern2
    boolean temp = false;
    if (flag == 1) {
        temp = judge();
    }
    if (temp || flag == 2) {
        doSomething();
    }

    // Pattern3
    if ((flag == 1 && judge()) || flag == 2) {
        doSomething();
    }

    // Pattern4
    switch (flag) {
    case 1:
        if (!judge()){
            break;
        }
    case 2:
        doSomething();
    default:
        break;
    }
}

Leaving aside minor variations, I wrote down all the patterns I could think of—did your answer match one of them?
I verified that they work, so they should all behave correctly.

4. Which One Do You Like?

Each of the four patterns above has its own pros and cons—
things like readability, whether the logic is normalized (not redundant), and how general-purpose it is.

First, Pattern 1 makes it easy to trace what happens for each value of flag.
If flag is a control variable in the program, there's a valid argument for wanting to follow the logic separately for each value.
However, as you can see, doSomething() is written twice, which is redundant. Also, it's harder to read at a glance as "basically, when flag is 2, we don't need to call judge()."

Next, Pattern 2 has no redundant calls, but I feel it's a bit hard to grasp at a glance. Above all, storing the intermediate result in a boolean variable makes it less intuitive.

Pattern 3 also has no redundancy, takes fewer lines, and looks the cleanest.
That said, because everything is packed onto a single line, it's likely to become hard to read if the variable named flag gets a longer name. In real code, judge() would probably have a much longer function name too, and flag might not even be an int—it might be a String compared with equals(). For example:

// Pattern3
if ((myMostFavoriteArtist.equals("ももいろクローバーZ") && judgeDoSomethingRunning()) || (myMostFavoriteArtist.equals("私立恵比寿中学") ) {
    doSomething();
}

Something like that.

Pattern 4 uses a switch statement and might feel intuitive to understand.
However, to understand this code, you have to know that "Java's switch statement works like a label jump, falling through to the lines below if you don't break." Usually(?) people write switch statements with a break at the end of every case, so surprisingly many people don't actually know about fall-through. I think some programming languages don't work that way either.
Also, Java's switch statement restricts which types you can pass in. If I remember right, you can't use reference types other than enum and String, nor floating-point numbers. The conditions must be exact equality checks too—no comparison operators allowed. We could use switch here because it was an exact match on an int, but from a language standpoint, switch is surprisingly restrictive.

5. Summary

There are many ways to write conditional branches, each with its own pros and cons, so you have to choose the right one for the situation.
Code is shared property among the whole team, so you also need to match the skill level of the people reading it.
Depending on your design philosophy and business requirements, what's most readable or resilient to change will differ.
There's no single silver bullet, so let's each be mindful when writing.
I hope this post gives you something useful to think about.