Thursday, June 19, 2008 11:43 AM
rendle
More thoughts on Enums vs. Adapters
Jared Parsons posted about using enums as a simplified version of the adapter pattern. In his code, each time the SomeAction method is called, it runs a switch against the private enum value and calls on to the relevant method.
Since C# 3.0 came along, with its lambdas and functional-style abilities, I've gotten used to thinking of methods as variables, which presents another way to do this sort of thing. Rather than having a public method, you can expose a delegate through a public property, and set the delegate according to the required behaviour. Using this method, Jared's example could look like this:
class Example
{
public Example(Kind kind)
{
switch (kind)
{
case Kind.Kind1:
this.SomeAction = ActionForKind1;
break;
case Kind.Kind2:
this.SomeAction = ActionForKind2;
break;
case Kind.Kind3:
this.SomeAction = ActionForKind3;
break;
default:
throw new InvalidOperationException("Invalid Kind");
}
}
public Func<int> SomeAction { get; private set; }
private int ActionForKind1() { return -1; }
private int ActionForKind2() { return 0; }
private int ActionForKind3() { return 1; }
}
I think that's just as readable. This technique can be used for more dynamic behaviour switching. Next time, I'll post a very simple technique for creating a delegate wrapper for long-running deterministic functions which caches in memory. Once you've got that, you can use this delegate property technique for switching between the cached and non-cached versions.
Filed under: functional programming