Pattern for Select Case on Object Type in C#

cdesign-patterns

I have read that doing a select case is often a code smell. There are cases however where an interface cannot solve my problem.

For instance, I have a set of date filter objects (last 7 days, last year, ect.) that implement a IDateFilter interface. In another part of the code, I need to determine the type of date filter so that the chart properties can be set. I may want to use a different chart tick interval for instance depending on the date filter.

The problem is I do not want to store this information in the date filter object as it is interface related and I do not want to couple the two.

How could a select case be avoided in this instance? Other than using select case on gettype or creating some enumeration for all the types and then exposing the type and doing a select case on that, I do not see a clean way to do this?

The decorator pattern comes to mind but even then I would still need a select case.

Any ideas?

if (type = last 7 days)
 set this property 
else if (type = last year)
 set this property to something different

I'm using asp net c# in case that makes a difference.

Best Answer

Create a data structure, such as a dictionary, which uses the type as the key and the value is the chart property. If you have multiple chart properties associated with a given type, then the value could be a ChartProperties object. So you have something like this:

ChartProperties chartProp;
if (propertiesMap.containsKey(currentFilter.getType()){
  chartProp = propertiesMap(currentFilter.getType());
}

I would make the properties map a subclass of a dictionary and then put the above code in a method on that class.

Related Topic