I'm arguing here with a colleague over two implementations of how to handle a processing logic:
VERSION 1:
public class SomeManager {
private readonly Dictionary<Type, Action<IData>> dataHandlers;
public SomeManager() {
dataHandlers = new Dictionary<Type, Action<IData>> {
{typeof(DataTypeOne), HandleDataTypeOne},
{typeof(DataTypeTwo), HandleDataTypeTwo},
{typeof(DataTypeThree), HandleDataTypeThird}
//... and so on
};
}
//... could be other code here
public void Process(IData data) {
var dataType = data.GetType();
if (!dataHandlers.ContainsKey(dataType )) {
Log.Error(string.Format("Unrecognized data type: {0}", dataType ));
return;
}
dataHandlers[dataType ](data);
}
private void HandleDataTypeOne(IDispatchData data) {
//...specific handling here
}
private void HandleDataTypeTwo(IData data) {
//...specific handling here
}
private void HandleDataTypeThree(IData data) {
//...specific handling here
}
}
VERSION 2:
public class SomeManager {
public SomeManager() {
}
//... could be other code here
public void Process(IData data) {
if (data is DataTypeOne) {
HandleDataTypeOne(data);
} else if (data is DataTypeTwo) {
HandleDataTypeTwo(data);
} else if (data is DataTypeThree) {
HandleDataTypeThree(data);
//other cases here
} else {
Log.Error(string.Format("Unrecognized data type: {0}", data.GetType()));
}
}
private void HandleDataTypeOne(IDispatchData data) {
//...specific handling here
}
private void HandleDataTypeTwo(IData data) {
//...specific handling here
}
private void HandleDataTypeThree(IData data) {
//...specific handling here
}
}
In our case, performance is not an issue.
We are talking here about a specific scenario of 5 data types.