Code of the week
This piece of code make me so happy:
private static IDictionary<string, Func<Stream, ICommand>> commandFactories = new Dictionary<string, Func<Stream, ICommand>> { //storage {"add", s => new AddCommand(s)}, {"append", s => new AppendCommand(s)}, {"cas", s => new CasCommand(s)}, {"delete", s => new DeleteCommand(s)}, {"prepend", s => new PrependCommand(s)}, {"replace", s => new ReplaceCommand(s)}, {"set", s => new SetCommand(s)}, // retrieval {"get", s => new GetCommand(s)}, {"gets", s => new GetsCommand(s)}, //modifications {"incr", s => new IncrCommand(s)}, {"decr", s => new DecrCommand(s)}, //misc {"flush_all", s => new FlushAllCommand(s)}, {"quit", s => new QuitCommand(s)}, {"version", s => new VersionCommand(s)}, };
This is something that I do quite often, and it is good to have a way to do it easily.
Comments
They look like memcached commands
You should have request commands from IoC container, not from the dictionary.
So what does it do, and why did you do it this way?
Have I just made a DSL?
public static void Main(string[] args)
love the dictionary lookups with the generic delegates/lambdas too.
as much as i'm interested in your code, i'm doubley interested in your design process. e.g., how much analyse/OO modelling you do before you start writing real code?
With tools like R#/svn is the up-front design pretty much dead for garage projects?
would like to read about the steps you take before you get to code. i ask because as a sophisicated practitioner, you take intermediate working steps for granted whilst someone at my level struggles to keep up sometimes.
The more I dig into C# 3.0 the more I infatuate with it.
Question...
private static IDictionary do you gain anything by using the IDictionary interface verse just using a regular Dictionary class?
I like using the most abstract type possible
What about
IDictionary<string, Func<Stream, ICommand>> CreateCommandFactories(IEnumerable<Type> types) {
return (
from type in types
select new {
Name = type.Name.Replace("Command", "").ToLowerInvariant(),
Factory = (Func<Stream, ICommand>)(s => Activator.CreateInstance(type, s))
}
).ToDictionary(
x => x.Name,
x => x.Factory
)
}
Of course better way would be to use Regex for parsing and Expression.Compile for constructor.
That involves reflection. I wanted this to be zero reflection effort
Ok, but Andrey suggested an excellent duplication removal.
I thought of it... what is more valuable? Avoiding reflection or avoiding duplication... In any case we have a tests ;)
Dmitry,
In this case, what I wanted was no reflection. The price paid for it is worth it, I think.
Comment preview