Use a method instead of if/else to conditionally assign to a variable

I’ve written code that assigns to a variable in each branch an if/else statement, but it always felt awkward. Here’s an example:

public Stuff getStuff() {
    // Other code...
    Thing foo;
    if (someValue == 5) {
        foo = getFooForFive();
    } else {
        foo = getOtherFoo();
    }
    // Other code...
}

This code looks simple, but it can be improved. Adding the final keyword expresses the intent slightly better and will result in a compilation error if you don’t assign a value:

// Slightly better:

public Stuff getStuff() {
    // Other code...
    final Thing foo;
    if (someValue == 5) {
        foo = getFooForFive();
    } else {
        foo = getOtherFoo();
    }
    // Other code...
}

Both of these solutions add require 6 lines of code and disrupt the flow for the reader. A ternary operator might fit on one line but only works for cases with two outcomes and can look ugly if the test is too long for one line.

The ideal solution is to break out the assignment code into its own method. This has the advantage of decluttering and simplifying the getStuff() method while also creating a new method that can easily be shared, changed and refactored later. In IntelliJ the Extract Method refactoring can do most of this work automatically.

// Much better:

public Stuff getStuff() {
    // Other code...
    Thing foo = getFooForValue(someValue);
    // Other code...
}

private Thing getFooForValue(int someValue) {
    if (someValue == 5) {
        return getFooForFive();
    } else {
        return getOtherFoo();
    }
}




Leave a Reply

Your email address will not be published. Required fields are marked *