简体   繁体   中英

Java - avoid switch statements for static functions

Check out this code -

switch(kind) {
     case "green" :
           GreenKind.doSomething(); // Static function
     break;
     case "white" :
           WhiteKind.doSomething(); // Static function
     break;
     case "blue" :
           BlueKind.doSomething(); // Static function
     break;
     case "yellow" :
           YellowKind.doSomething(); // Static function
     break;
}

There is a way to avoid the switch statement? as it smells real bad.

Maybe to somethnig like this? -

kinds.get(kind).doSomething();

The problem with my solution is that the functions are static, and i can't implement an interface with static functions. If you didn't understood why i wrote interface its because i wanted to use polymorphism in my solution above.

I would have an enum like so:

enum Kind {
    GREEN {
        @Override
        public void doSomething() {
            GreenKind.doSomething();
        }
    },
    WHITE {
        @Override
        public void doSomething() {
            WhiteKind.doSomething();
        }
    };

    public abstract void doSomething();
}

And pass around an enum constant, for example this method:

public static void invoke(Kind kind) {
    kind.doSomething();
}

and call it like:

invoke(Kind.GREEN);

This way looks cleaner, and moreover it's safer, as you can have only a fixed set of inputs.

You can use an enum. Example for a single entry enum:

public enum Kind
{
    GREEN("green")
    {
        @Override
        public void doSomething() { /* do something */ }
    };

    private final String asString;

    public abstract void doSomething();

    Kind(final String asString)
    {
        this.asString = asString;
    }

    @Override
    public String toString() { return asString; }
}

In code, you would then do Kind.valueOf(kind.toUppercase()).doSomething(); .

This would also allow you to get rid of {Green,Red}Kind with a little work: just put all the logic into the enum.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM