Search code examples
javamethodsfully-qualified-naming

Explicit method naming or generic method name with call purpose parameter


I sometimes stumble upon a decision for method naming on public API methods.

Variant A:

public void play();
public void stop();
public void pause();

Variant B:

public enum CallType {
            PLAY,
            STOP,
            PAUSE
        }
public void execute(CallType type);

I think for the API client it is more convenient to have interface of variant A, since no parameter(and checking!) is needed.

But I also think with variant B the public interface is also smaller and the task for the developer is easier.

What is your opinion about these approaches?


Solution

  • If the number of call types is reasonably low, I'd say it is worth having separate methods for each action (variant A). It makes the interface easier to read and you don't have to divert the user of your class to an additional JavaDoc page (of the enum) in order to be informed on which are his options of using your interface. As the number of call types grows, you might get an interface with larger contract (that is, a higher number of methods), so it might be worth using the enum. But be aware that in this case your execute method might grow too large (probably with a switch statement with a lot of cases).

    I think the answer should be given by what reasonably means, and there's no exact answer to this. It depends on developer preferences, coding standards in your organization, static code check rules (if you have an analyzer) and so on and so forth.