Do nothing in a case of an enhanced switch
Asked Answered
G

1

13

I have following enhanced switch case

@Override
public MultivaluedMap<String, String> update(MultivaluedMap<String, String> incomingHeaders,
        MultivaluedMap<String, String> clientOutgoingHeaders) {

    switch (authMethod) {
        case BASIC -> clientOutgoingHeaders.add("Authorization", basicAuth("admin", "admin"));
        case BEARER -> clientOutgoingHeaders.add("Authorization", "Bearer" + " " + getAccessTokenFromKeycloak());
        case SKIP -> System.out.println(); // How can I remove this?
    }
    return clientOutgoingHeaders;
}

where as authMethod is a

enum AuthMethod{
        BASIC,
        BEARER,
        SKIP
    }

If authMethodis SKIP I simply want the code to do nothing. I don't want to remove the case.

I am aware, that I could work around this problem in other different ways, but I am curious if this works with an enhanced switch.

Also I am aware, that I could just remove the SKIP case. That is simply not what I want, because I want to make clear, that SKIP does nothing in that case.

This is what I have tried

case SKIP -> {};
case SKIP -> ();

How can I do nothing in a case of an enhanced switch statement?

Galton answered 7/4, 2022 at 17:34 Comment(4)
I think it's already clear to any competent Java programmer that, if a case is not present in the switch, then it simply does nothing. What you're describing is akin to putting an empty else clause on an if statement; nobody advocates for that.Ashraf
What happened when you tried case SKIP -> {};?Ashraf
@RobertHarvey IDE (IntelliJ) is complaining 'case', 'default' or '}' expected. I tried that.Galton
@RobertHarvey "it's already clear to any competent Java programmer that, if a case is not present in the switch, then it simply does nothing" This can also mean that someone introduced new enum constant and forgot to adjust corresponding switch statements to handle the new case. This in turn leads to runtime errors, while it's better to catch them at compile timeExplicable
C
20

This is so close!

case SKIP -> {};

You just had one extra semicolon! Remove it and it compiles!

case SKIP -> {}

See the syntax for a SwitchRule in the Java Language Specification:

SwitchStatement:
switch ( Expression ) SwitchBlock

SwitchBlock:
{ SwitchRule {SwitchRule} } 
{ {SwitchBlockStatementGroup} {SwitchLabel :} }

SwitchRule:
SwitchLabel -> Expression ; 
SwitchLabel -> Block 
SwitchLabel -> ThrowStatement

Notice how, if it is an expression, like your add calls, you need a semicolon after it. If you use a block, like {}, you should not add a semicolon.

Caton answered 7/4, 2022 at 17:47 Comment(1)
Thanks! I am used to put; everywhere. :D btw: a static method which does nothing like doNothing and a static import to it looks also very nice.Galton

© 2022 - 2024 — McMap. All rights reserved.