Damian U
Damian U

Reputation: 381

How to avoid if statements with equals when using enum type?

Does exists some way to avoid many if statements when use enum type? Maybe I should use some design patterns instead use if statements.

I have many cases in my code which looks like this: // pseudo code

public void methodOne() {    
    if(User.Type.SomeType == user.Type && User.Type.SecondType == user.Type)
        doSomething();
}

public void methodTwo() {
    if(!User.Type.OtherType == user.Type && !User.Type.SecondType == user.Type)
        throw new BadTypeException();
    doSomething();
}

Upvotes: 0

Views: 158

Answers (3)

john16384
john16384

Reputation: 8044

Use an EnumSet:

private static final Set<User.Type> SET = EnumSet.of(User.Type.SomeType, User.Type.SecondType);

if (SET.contains(user.type)) {
}

Upvotes: 5

Sergii Bishyr
Sergii Bishyr

Reputation: 8641

Of course you can create a utility class and move those checks to static method, but this is not OOP way and won't fix your design.

Instead I will suggest you to think about subclassing you User. So instead of having User.Type you will have interface User or abstract class User and subtypes:

class AdminUser implements User

class GuestUser implements User

And so on. Method doSomething should be moved to your User interface and implemented by subclasses. And you will just ask for your user to doSomething.

Upvotes: 0

Catalin
Catalin

Reputation: 474

Personally I like using vararg functions for this case in particular

private static boolean matchesAnyState(User.Type type, User.Type... types) {
    for (User.Type listType: types) {
        if (type.equals(listType)) {
            return true;
        }
    }
    return false;
} 

Upvotes: 1

Related Questions