Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to turn this piece of code into one line of code?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading