Instead of a simple switch statement - Luca Bolognese

Instead of a simple switch statement

Luca -

☕ 1 min. read

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

Comments

drysart@gmail.com

2007-08-31T17:16:42Z

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

MichaelGiagnocavo

2007-08-31T17:35:45Z

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

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

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

Doeke Zanstra

2007-09-18T08:53:35Z

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

0 Webmentions

These are webmentions via the IndieWeb and webmention.io.