Shaik Zakir Hussain Shaik Zakir Hussain - 1 year ago 84
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 {

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


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

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

Answer Source

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.


void doSomething(e enumParam) {;


void doSomething(e enumParam) {
    switch(enumParam) {
        case 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download