Instead of a simple switch statement …


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);
    }

Comments (5)

  1. drysart@gmail.com says:

    It looks so silly when someone /else/ does it….

  2. MichaelGiagnocavo says:

    Yes, let the functions flow through you. Add a bit of aliasing and easier delegate syntax and succinctness incarnate.

  3. Bill Mill says:

    This is from python 101, except without all the <><<type>> business; It’s an excellent way to seperate code from data.

  4. Greg says:

    Please 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#.  

  5. This 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