Instead of a simple switch statement
Luca -
☕ 1 min. read
This is Luke‘s kind of code. I might be catching the virus
abstract class QIFParserBase { public enum LoadOptions { All, Prices, Securities, Transactions } static readonly Dictionary<LoadOptions, Action<QIFParserBase, string[]>> parseFuncs = new Dictionary<LoadOptions, Action<QIFParserBase, string[]>> { {LoadOptions.All, (q,c) => q.ParseAll(c)}, {LoadOptions.Prices, (q,c) => q.ParsePricesBlocks(c)}, {LoadOptions.Securities, (q,c) => q.ParseSecurityBlocks(c)}, {LoadOptions.Transactions, (q,c) => q.ParseTransactionBlocks(c)} }; public QIFParserBase(string fileName, LoadOptions opt) { string content = File.ReadAllText(fileName); string[] blocks = content.Split(new string[] { "!Type:", "!Option:" }, StringSplitOptions.RemoveEmptyEntries); parseFuncs[opt](this,blocks); }
0 Webmentions
These are webmentions via the IndieWeb and webmention.io.
5 Comments
Comments
drysart@gmail.com
2007-08-31T17:16:42ZIt looks so silly when someone /else/ does it....
MichaelGiagnocavo
2007-08-31T17:35:45ZYes, let the functions flow through you. Add a bit of aliasing and easier delegate syntax and succinctness incarnate.
Bill Mill
2007-08-31T23:29:55ZThis is from python 101, except without all the <><<type>> business; It's an excellent way to seperate code from data.
Greg
2007-09-17T10:07:22ZPlease don't put that into production code. This type of cute code will serve to hide the actual functionality or business reasons behind the code. It will greatly increase the cost to support and maintain production code. It is simple when presented out of context here but when combined with dozens of similar approaches in a production system, it is unmaintainable. I've seen this in three different environments C with structs of function pointers, C++ and C#.
Doeke Zanstra
2007-09-18T08:53:35ZThis looks a bit of a scripting solution. I'm not sure I like it. OK, it's a cool programming technique, but does it solve a problem?
In comparison to a switch statement:
1) The code executes a bit slower
2) It adds a layer of indirection, so it's more complex, thus harder to read
3) "It's an excellent way to seperate code from data". Is it?
The enum, and the Dictionary are still seperate... I would like to have java enums in c#. That way, you can combine the enum-items with the specific delegate.
That way, the code is shorter, one (very small) step faster than the code above, but above all: it's easier to understand (provided, you know the syntax of course).
http://java.sun.com/j2se/1.5.0/docs/guide/language/enums.html