dimanche 19 mai 2019

static methods in Enum (in Java)

Main question: Is it bad practice to use static methods in enums?

2 examples i am looking into.

  1. based on the helpful question&Answer: Implementing Singleton with an Enum (in Java)

    After creating the INSTANCE enum, we can create all the methods static and that way ease the invocation: MySingleton.INSTANCE.someMethod() vs MySingleton.someStaticMethod()

  2. for generic logic

public enum BlaBla {
    A(/*otherData*/, Arrays.asList(SomeClass1.class, SomeClass4.class)),
    B(/*otherData*/, Arrays.asList(SomeClass2.class),
    C(/*otherData*/, Arrays.asList(SomeClass3.class);
    ...
    constructor & methods
    ...
public static List<Class<?>>validClasses() {
    return Arrays.asList(SomeClass1.class, SomeClass2.class, SomeClass3.class, SomeClass4.class);
}

whats wrong with the first example? and are there any issues or bad practices in the second example?

Aucun commentaire:

Enregistrer un commentaire