Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch on an if statement?

I am a bit of a beginner with coding, so can someone please tell me if it is possible to do something like this in Java, in a void result type?

switch (if this != null {return this;}
            else {return that;}) {

    case "This": blah
        break;
    case"That": blah
        break;
}

Also, can anyone tell me the most efficient way to do a switch statement with two variables? Thanks! :)

like image 726
Aden Diamond Avatar asked Dec 10 '22 08:12

Aden Diamond


2 Answers

Use the ternary operator:

switch (this != null ? this : that) {
    ...
}

Or the Optional class:

switch (Optional.ofNullable(this).orElse(that)) {
    ...
}
like image 88
John Kugelman Avatar answered Dec 12 '22 21:12

John Kugelman


The simple non answer: don't do such a thing. Because such code is hard to read and maintain.

If at all, do something like

switch(computeLookupValue(whatever)) 

But your idea to do that many things in a few lines of code is bad practice.

And then also forget that part about efficiency. In Java, you write efficient code by writing simple code that can be optimized by the just in time compiler for you. Trying to write "smart" Java source code can quickly lead to you preventing the JIT from doing its job!

like image 32
GhostCat Avatar answered Dec 12 '22 21:12

GhostCat