Shaik Zakir Hussain Shaik Zakir Hussain - 15 days ago 5
Java Question

Methods with different names vs single method with different enum params in java

I have a use case where I need to call a similar logic, with different enum parameters. Although passing in the enum param gives good code reusability, some may argue that the other way of creating multiple functions with names denoting its operation gives good readability. Is there a strong opinion in programming community of choosing one over the other?

For eg.

enum e {
aaa,
bbb
};

foo(e enumParam) {
// method impl using enumParam
}

Vs.

fooAaa() {
// method impl using enum e.AAA
}

fooBbb() {
// method impl using enum e.BBB
}

Answer

If you must make a method that dispatches on the enum's type because you cannot place the logic in an enum's instance method, the first approach offers better code reuse in situations when the caller has an instance of e that comes from some other place.

Compare

void doSomething(e enumParam) {
    Foo.foo(enumParam);
}

vs.

void doSomething(e enumParam) {
    switch(enumParam) {
        case e.aaa: Foo.fooAaa(); break;
        case e.bbb: Foo.fooBbb(); break;
        default: ... // Throw some exception
    }
}

In the first case callers simply forward enumParam to foo. In the second case, however, callers need to dispatch on e themselves, repeatedly using similar logic to route the call to fooAaa vs. fooBbb.

Comments