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?

有帮助吗?

解决方案

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.

其他提示

No. You create separate class for each of the methods and use virtual calls to pick which one to call. Something like this.

If you have two algorithms, that are called through same API, but which do something slightly different, then the most idiomatic way is to create base class or interface that defines the API and then create a class for each algorithm that implements this interface. This is even better if you want to add new algorithms, because you don't have to change the class that contains those methods, you just add new class. Thus abiding by Open-closed principle.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top