I’m a beginner to Java and was wondering if there is a way to rewrite the below code in 1 one line while keeping its functionality the same?
private boolean colour_chosen(Colour Colour, boolean red, boolean blue, boolean yellow) {
if (Colour instanceof redColour) {
if (red) return true;
else return false;
} else if (Colour instanceof blueColour) {
if (blue) return true;
else return false;
} else if (Colour instanceof yellowColour) {
if (yellow) return true;
else return false;
} else {
return false;
}
}
>Solution :
You can replace the if blocks by logical expressions. That way, the entire method body reduces to:
return (Colour instanceof redColour && red) || (Colour instanceof blueColour && blue) || (Colour instanceof yellowColour && yellow);
However, it’s questionable how readable this is; having a single expression is fine, but I would still split it across lines.
The parentheses in the code above are unnecessary because && has precedence over || but many people prefer them.
In general, code of the form if (condition) return true; else return false; can — and should! — always be replaced by return condition;.