Question

I am working on a project and I am using Intellij IDEA. While I was writing I got a notification that my if-statement could be simplified. (Note that I am still new to coding)

It says:

Reports if statements which can be simplified to single assignment or return statements. For example:

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

can be simplified to

return foo();

How does this work? Say foo() is the number 4, wouldn't this just return 4 instead of true? What am I misunderstanding?

Edit

Here is the code I am writing:

if (row > 0 && row < 4 && col > 0 && col < 4) {
    return false;
} else {
    return true;
}

and it can be simplified to:

return !(row > 0 && row < 4 && col > 0 && col < 4);

I just don't understand how this is simplified.

Was it helpful?

Solution

(row > 0 && row < 4 && col > 0 && col < 4) is itself a boolean (true or false).

We can break it down as boolean && boolean && boolean && boolean as < and > operators return booleans. Likewise, a boolean and a boolean is a boolean, therefore the entire expression is a boolean and can be returned as such.

You can think about it as such:

  • For the row, you have a number, so you can say "how many" or "which number". Same for the column.
  • For the comparisons, you can ask: If x and y are numbers, then is x < y? The answers possible are true or false. Hence boolean.
  • For &&, ||, or !, you can ask yourself: "If a and b are statements (true or false), then "a and b are both true" is either true or false. Same for "or", or "a is not true". The results are true and false.

Now you can look at the if, and read it as "if foo is true, then return false. Otherwise, return true". This clearly simplifies to "return the opposite of foo" or, "return not foo".

OTHER TIPS

Your Foo() method returns a boolean value, so it will be true or false. Therefor, you do not need to add redundancy by adding an if statement to check for true or false, and then return true or false.

For an if statement to compile, the condition between parenthesis, has to be a boolean.

So, if you can put the method foo as the condition of an if, it's because it returns a boolean.

Therefore, you could write:

return foo(); 

In your particular case, the expression !(row > 0 && row < 4 && col > 0 && col < 4) evaluates to true or false, Therefore you could write:

return !(row > 0 && row < 4 && col > 0 && col < 4);

I have similar code like you:

if (other.getClassAbbr().equals(this.getClassAbbr())
        && other.getInstance().equals(this.getInstance())) {
    return true;
}

return false;

After thinking of it, I take the suggestion: 'if' statement can be simplified

Then the code be changed to:

    return other.getClassAbbr().equals(this.getClassAbbr())
            && other.getInstance().equals(this.getInstance());

Yes, code gets clean.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top