Instead of a simple switch statement

-

This is Lukes kind of code. I might be catch­ing 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);
    }

Tags

5 Comments

Comments

drysart@gmail.com

2007-08-31T17:16:42Z

It looks so silly when some­one /else/ does it….

MichaelGiagnocavo

2007-08-31T17:35:45Z

Yes, let the func­tions flow through you. Add a bit of alias­ing and eas­ier del­e­gate syn­tax and suc­cinct­ness in­car­nate.

This is from python 101, ex­cept with­out all the <><<type>> busi­ness; It’s an ex­cel­lent way to seper­ate code from data.

Please don’t put that into pro­duc­tion code.  This type of cute code will serve to hide the ac­tual func­tion­al­ity or busi­ness rea­sons be­hind the code. It will greatly in­crease the cost to sup­port and main­tain pro­duc­tion code.      It is sim­ple when pre­sented out of con­text here but when com­bined with dozens of sim­i­lar ap­proaches in a pro­duc­tion sys­tem, it is un­main­tain­able.   I’ve seen this in three dif­fer­ent en­vi­ron­ments C with structs of func­tion point­ers, C++ and C#.  

Doeke Zanstra

2007-09-18T08:53:35Z

This looks a bit of a script­ing so­lu­tion. I’m not sure I like it. OK, it’s a cool pro­gram­ming tech­nique, but does it solve a prob­lem?
In com­par­i­son to a switch state­ment:
1) The code ex­e­cutes a bit slower
2) It adds a layer of in­di­rec­tion, so it’s more com­plex, thus harder to read
3) It’s an ex­cel­lent way to seper­ate code from data”. Is it?
The enum, and the Dictionary are still seper­ate… I would like to have java enums in c#. That way, you can com­bine the enum-items with the spe­cific del­e­gate.
That way, the code is shorter, one (very small) step faster than the code above, but above all: it’s eas­ier to un­der­stand (provided, you know the syn­tax of course).
http://​java.sun.com/​j2se/​1.5.0/​docs/​guide/​lan­guage/​enums.html