Richard
Richard

Reputation: 6116

Java enum initialization best practices

I have a question regarding best practices when dealing with enums in Java. Let's say I have a java class and an enum class like so:

public class Foo {
    private final FooEnum fooEnum;

    public Foo(FooEnum fooEnum) {
        this.fooEnum = fooEnum;
    }

    public Foo(String fooEnum) {
        this.fooEnum = FooEnum.valueOf(fooEnum);
    }
}

public enum FooEnum {
    FOO1,
    FOO2,
    FOO3
}

My question is this: Is it considered good practice to offer a 2nd constructor that takes in a string to initialize the enum so the user can choose either to pass an enum or it's string equivalent? If not, what is the alternative? Should the user be responsible for converting the string into an enum?

Upvotes: 0

Views: 769

Answers (1)

Andy Turner
Andy Turner

Reputation: 140309

No, it is bad practice to do that:

  1. You're just adding code which may not be used: YAGNI, as they say. And if you do need to get a FooEnum for a string, is it that bad to say new Foo(FooEnum.valueOf(str))?

  2. What if I pass in the string "bibble": it's not a problem in Foo that causes the exception to be thrown, so don't involve Foo in that problem.

    By providing a String constructor, you are saying that "you can pass me any string" (of which there are practically infinitely many); by providing a FooEnum constructor, you are saying that "you can pass me any FooEnum", of which there are a very small number. So you're limiting the space of valid inputs substantially; and the user isn't left guessing what a valid input might be.

The alternative: since you need an instance of FooEnum in your Foo, make the user of the class pass in an instance of FooEnum.

Upvotes: 8

Related Questions