Search code examples
c#oopenumstheory

Use enum for logic in method signature?


Assume we have an enum (trivial example for the sake of demonstration)

public enum EnumTest{
valueA,
valueB
}

Lets then assume we have a method that a consumer calls that will do something based on the current value of the enum. What is the better of of doing this? Is it to

Have a method that takes in the enum , and then depending on the value of this enum carries out the action. ie

 public void DoSomething(EnumTest emumVal){
 //common code here    

switch(enumVal){

 case EnumTest.valueA: doSomething();
                       break;
 case EnumTest.valueB: doSomethingElse()
                        break;
 }
}

This seems to be a favourite method among people I have asked for advice, but I know that a method should do one thing and one thing only. Having it do slightly different things based on an enum leaves me thinking that there is the possibility that this method could be very large and unwieldy if more enums are added

The other option seems to be to have explicit methods for each of enums.ie

public void DoSomethingForValueA(){

}

public void DoSomethingForValueB(){

}

but some fellow programmers say this is excessive and is a waste of time.

I was wondering what the correct way would be to do something like this?


Solution

  • They are both correct. If you care about encapsulation and SRP, go with the second one.

    public void LogWarning() { Log(Severity.Warning); }
    public void LogError() { Log(Severity.Error); }
    private void Log(Severity severity) { ... };
    

    The first one is also correct, however enums can grow and you will find yourself in a situation where you call a different methods based on the option. If you have only a few options and executer a few lines of code for them, the first one is more concise.

    Also depends on how clear your API do you want. One method taking a parameter is clearly more concise then 10 methods with similar names without a parameter.