Friday, February 02, 2007

This describes yet another way to do things.  Suppose you have input coming from a common source, but based on the content of that input, you want your program to do different things.  Naturally, the first thing you think of is the switch statement.  But I've stumbled across an interesting alternative.

Here is a simplified class in C# that uses a switch statement:

public class MyGame: IGame {
   
    public string ExecuteCommand(string command, string parameter) {
        string result;
        switch (command) {
            case "ECHO":
                result = DoEcho(parameters);
                break;
            case "JOIN":
                result = DoJoin(parameters);
                break;
            case "READY":
                result = DoReady(parameters);
                break;
            default:
                result = DoError();
                break:
        }
        return result;
    }
   
    public string DoEcho(string parameters) {
        string result;
        // code here
        return result;
    }
   
    public string DoJoin(string parameters) {
        string result;
        // code here
        return result;
    }
   
    public string DoReady(string parameters) {
        string result;
        // code here
        return result;
    }
   
    public string DoError() {
        string result;
        // code here
        return result;
    }
}

I decided to play around with generics to see if I could come up with an alternative to "switch".  By using a Dictionary of delegates, I can look up what the appropriate action to take would be, and then do it in a generic fashion.

public class MyGame: IGame {
   
   
private delegate string CommandHandler(string parameters);
   
protected Dictionary<string, CommandHandler> commandHandlers =
new Dictionary<string, CommandHandler>();
   
    public MyGame() {
        commandHandlers["ECHO"] = new CommandHandler(DoEcho);
        commandHandlers["JOIN"] = new CommandHandler(DoJoin);
        commandHandlers["READY"] = new CommandHandler(DoReady);
    }
   
    public string ExecuteCommand(string command, string parameter) {
        CommandHandler handler;
        if (commandHandlers.TryGetValue(command, out handler)) {
            return handler.Invoke(parameter);
        } else {
            return DoError();
        }
    }
   
    // handler code is same above.
   
}

I don't know about you, but this is much more satisfying at varying levels.  I've never liked the switch statement syntax, ever, and this code is easier on the eyes.  This transforms the dispatch mechanism from a procedural approach to a table-driven approach.  The one disadvantage is that all the dispatch methods must have the same figure, but usually uniformity is a welcome attribute to code.  One cool thing is that by adding a new handler, Resharper will automagically generate the signature for the new dispatch method.

A place where this approach might be useful is by assigning abstract factory methods as delegates.  Those have to be uniform, by design contract.

One thing I would like to see is the ability to assign all of the elements in the dictionary in a single statement.  I understand this will be a new feature in C# 3.0, but I haven't experimented with that yet.  I just downloaded the SDK yesterday!

posted on Friday, February 02, 2007 11:10:53 AM (Central Standard Time, UTC-06:00) by Christopher S. Velazquez
digg it!     del.icio.us     Live it!     Newsvine     Facebook #    Comments [5] Trackback
Related posts:
Running .NET Code from Microsoft Office 2003
Why Office 2007 Really Does Rock
Developing Software that Doesn't Suck
Resharper 2.5 is now available
Customizing a NAnt Build Script with C#
SubSonic - The Zero Code DAL
Tracked by:
http://www.google.com/search?q=taafrgcg [Pingback]
http://www.hotelbusiness.com/links/news/news_brief.asp?ID=33732 [Pingback]
http://www.kerkuk.net/hizmetler/kitaplar/kitap.aspx?kitap=375215692 [Pingback]
http://www.kerkuk.net/hizmetler/kitaplar/kitap.aspx?kitap=345490743 [Pingback]
http://www.spacecoalition.com/press%20releases.cfm?aid=340 [Pingback]
http://italmed.edraspa.it/med.browsing.scheda.cfm?topic_ID=255 [Pingback]
http://www.hotelbusiness.com/links/news/news_brief.asp?ID=33733 [Pingback]
http://www.kerkuk.net/hizmetler/kitaplar/kitap.aspx?kitap=218806823 [Pingback]
http://www.allwatchers.com/MovieRView.asp?BRID=157704 [Pingback]
http://www.rupaul.com/newstore/shopexd.asp?id=158 [Pingback]
http://www.addlink.es/productos.asp?pid=783 [Pingback]
http://www.spacecoalition.com/press%20releases.cfm?aid=318 [Pingback]
http://www.spacecoalition.com/press%20releases.cfm?aid=321 [Pingback]
http://www.stamford.edu.my/Courses/details.asp?id=69 [Pingback]
http://www.addlink.es/productos.asp?pid=797 [Pingback]
http://www.stamford.edu.my/Courses/details.asp?id=75 [Pingback]
http://www.stamford.edu.my/Courses/details.asp?id=76 [Pingback]
http://www.stamford.edu.my/Courses/details.asp?id=80 [Pingback]
http://www.reefcorner.org/forum/topic.asp?TOPIC_ID=79697 [Pingback]
http://www.imarest.org/eshop/product.asp?ID=3855 [Pingback]
http://www.medicalsearch.com.au/products/printarticle.asp?id=30944 [Pingback]
http://www.imarest.org/eshop/product.asp?ID=3878 [Pingback]
http://www.medicalsearch.com.au/products/printarticle.asp?id=30947 [Pingback]
http://www.imarest.org/eshop/product.asp?ID=3872 [Pingback]
http://www.reefcorner.org/forum/topic.asp?TOPIC_ID=79783 [Pingback]
http://www.reefcorner.org/forum/topic.asp?TOPIC_ID=79781 [Pingback]
http://www.imarest.org/eshop/product.asp?ID=3879 [Pingback]
http://www.wiaa.com/news.asp?ID=pubnzepc [Pingback]
http://www.jobpostings.ca/resource.cfm?id=121 [Pingback]
http://www.medicalsearch.com.au/products/printarticle.asp?id=30978 [Pingback]
http://www.wiaa.com/news.asp?ID=wsoeiozb [Pingback]
http://www.seattlesutton.com/Blog/default.asp?BlogID=48 [Pingback]
http://www.seattlesutton.com/Blog/default.asp?BlogID=61 [Pingback]
http://womenshealthmatters.com/news/news_show.cfm?number=386553771 [Pingback]
http://www.hawaiianhumane.org/news/display.asp?id=189 [Pingback]
http://www.jobpostings.ca/resource.cfm?id=139 [Pingback]
http://www.washingtonblade.com/thelatest/thelatest.cfm?blog_id=20518 [Pingback]
http://www.seattlesutton.com/Blog/default.asp?BlogID=74 [Pingback]
http://www.washingtonblade.com/thelatest/thelatest.cfm?blog_id=20574 [Pingback]
http://www.southernvoice.com/blog/index.cfm?blog_id=20591 [Pingback]
http://www.enterprisestrategygroup.com/OurTeam/TeamBio.asp?TeamMemberID=56 [Pingback]
http://www.hawaiianhumane.org/news/display.asp?id=228 [Pingback]
http://www.enterprisestrategygroup.com/OurTeam/TeamBio.asp?TeamMemberID=71 [Pingback]
http://www.cobizmag.com/wheels_printable.asp?wheel_id=319 [Pingback]
http://www.southernvoice.com/blog/index.cfm?blog_id=20612 [Pingback]
http://www.freeerisa.com/insightnew/forum.asp?id=10120 [Pingback]
http://www.cobizmag.com/wheels_printable.asp?wheel_id=317 [Pingback]
http://www.assinform.it/casibusiness/02.asp?iNEWLIS_ID=1155 [Pingback]
http://www.belfastmet.ac.uk/courses/leaflet.asp?course_id=2469 [Pingback]
http://www.belfastmet.ac.uk/courses/leaflet.asp?course_id=2527 [Pingback]
http://www.ckua.org/about/bodies/StaffDirDetails.cfm?p_id=35028 [Pingback]
http://www.ckua.org/about/bodies/StaffDirDetails.cfm?p_id=35038 [Pingback]
http://www.ckua.org/about/bodies/StaffDirDetails.cfm?p_id=35045 [Pingback]
http://www.teach-now.org/dispstatehtml.cfm?statepageid=1433 [Pingback]
http://www.ckua.org/about/bodies/StaffDirDetails.cfm?p_id=35061 [Pingback]
http://www.google.com/search?q=xiilaswk [Pingback]
http://www.google.com/search?q=jupgkqvi [Pingback]
http://www.ninthhouse.com/company/releases/release.asp?article=807 [Pingback]
http://www.ninthhouse.com/company/releases/release.asp?article=817 [Pingback]
http://www.boatsdepot.org/boat.asp?id=5744 [Pingback]
http://www.unsam.edu.ar/infodigital/infodigital.asp?id=2262 [Pingback]
http://www.cultuur.rotterdam.nl/info/organisatie.cfm?code=1757 [Pingback]
http://www.ncsconline.org/d_tech/ctb2/view_cs_cont.asp?NCSC_CMS_CONTENT_ID=2649 [Pingback]
http://www.irishabroad.com/yourroots/familynames/SurnameView.asp?id=1916 [Pingback]
http://www.arccores.com/news/PressRelease.html?id=1226 [Pingback]
http://www.squash.ca/f/story_detail.cfm?id=2842 [Pingback]
http://www.squash.ca/f/story_detail.cfm?id=2814 [Pingback]
http://www.v8central.com/wrc/racenews.asp?newsitem=376 [Pingback]
http://www.89fm.com.br/promo/?ID=1677 [Pingback]
http://www.arabgreekchamber.gr/en/news.asp?NID=142 [Pingback]
http://www.topeducationguide.com/article_details.asp?article_id=537 [Pingback]
http://www.labautomation.org/LA09/getPosterDetails.cfm?cid=248890969 [Pingback]
http://www.rosariofutbol.com/redir.asp?id=3161 [Pingback]
http://www.addisongallery.com/showbio.asp?id=2563 [Pingback]
http://www.addisongallery.com/showbio.asp?id=2521 [Pingback]
http://www.pdmdb.org/content.asp?contentid=1496 [Pingback]
http://www.pdmdb.org/content.asp?contentid=1500 [Pingback]
http://www.google.com/search?q=rnkesoyq [Pingback]
http://www.ellisislandrecords.org/STORY/story_detail.asp?id=2262 [Pingback]
http://www.89fm.com.br/promo/?ID=1691 [Pingback]
http://www.google.com/search?q=pwfnrmii [Pingback]
http://www.cashluna.org/opciones/print.cfm?id=2304 [Pingback]
http://www.google.com/search?q=vrfcqpoa [Pingback]
http://www.google.com/search?q=qgfzwtvn [Pingback]
http://www.google.com/search?q=txvgsanw [Pingback]
http://www.google.com/search?q=gncsgmqy [Pingback]
http://wound.smith-nephew.com/at/Standard.asp?NodeId=867302634 [Pingback]
http://wound.smith-nephew.com/at/Standard.asp?NodeId=844211503 [Pingback]
http://www.gogay.co.il/yoman/DiaryPost.asp?id=22510 [Pingback]
http://www.kerkuk.net/hizmetler/kitaplar/kitap.aspx?kitap=947563798 [Pingback]
http://www.google.com/search?q=esdjmxdi [Pingback]
http://www.kmisetas.com.br/pergunta.asp?cod=538 [Pingback]
http://www.blackwebportal.com/Yellow/myShop.cfm?ID=7053 [Pingback]
http://www.blackwebportal.com/Yellow/myShop.cfm?ID=7055 [Pingback]
http://abc.soapsindepth.com/interviews/feature.asp?FeatureID=460 [Pingback]
http://www.dncustoms.gov.vn/traloi/traloi1.asp?key=9272 [Pingback]
http://aik.pi.se/guestbook/original.asp?message_id=677514056 [Pingback]
http://www.offshore.no/prosjekter/dodetails.aspx?Id=356 [Pingback]
http://www.dubainetwork.com/events/details.asp?id=98 [Pingback]
http://www.google.com/search?q=kdwgmfvj [Pingback]
http://www.frenchleague.com/ligue1/lireArticle.asp?idArticle=16438 [Pingback]
http://www.jobs-me.com/viewjobdetails.asp?orderno=605774483 [Pingback]
http://www.graduate-recruitment.co.uk/blogs/blog-detail.asp?bid=176 [Pingback]
http://www.ewi.org/njc/project_details.asp?ID=220 [Pingback]
http://www.sinai.org/careers/career_detail.asp?job_id=752 [Pingback]
http://jhmmi.jhsph.edu/malaria/calendar/event_detail_info.cfm?event_id=322 [Pingback]
http://www.sinai.org/careers/career_detail.asp?job_id=754 [Pingback]
http://www.execunet.com/m_releases_content.cfm?id=4708 [Pingback]
http://www.careers.ncl.ac.uk/vacsonline/search/ngrfDetail.asp?vacID=32658 [Pingback]
http://www.aiou.edu.pk/Programmes.asp?PID=1013 [Pingback]
http://www.maimonides.edu/carreras_ficha_imprime.asp?car=398 [Pingback]
http://www.frontera.info/Perfiles/?u=niuirlos [Pingback]
http://www.bugs.bham.ac.uk/getinvolved/societies_pop.asp?ID=770 [Pingback]
http://www.frontera.info/Perfiles/?u=wvonashk [Pingback]
http://www.andersonsec.moe.edu.sg/web1/news_details.asp?newsid=99 [Pingback]
http://www.fdtc.edu/AboutUs/calendar/detail.asp?ID=3736 [Pingback]
http://www.kremlin.museum.ru/en/main/editions/?PUBLICATION_ID=867 [Pingback]
http://www.unioeste.br/servicos/centraleventos/lista_evento.asp?codvalue=665 [Pingback]
http://www.stmc.qld.edu.au/showitem.asp?pid=8095 [Pingback]
http://www.nu.edu.pk/NewsDetails.aspx?nid=823 [Pingback]
http://www.seplan.rn.gov.br/noticia.asp?codnoticia=348 [Pingback]
http://www.nu.edu.pk/NewsDetails.aspx?nid=815 [Pingback]
Friday, February 02, 2007 12:34:37 PM (Central Standard Time, UTC-06:00)
Very cool approach.
Nelson Montalvo
Monday, February 05, 2007 5:56:22 PM (Central Standard Time, UTC-06:00)
Nice and a new approach Chris.

One of the most popular alternative approaches to a switch statement is the wisely used STRATEGY pattern. Ironically that too isn't completely devoid of the switch statement or for that matter any other decision making mechanism, because it needs to return the right strategy.

I do agree that using delegates allows for more flexibility through code.
Monday, February 05, 2007 8:10:52 PM (Central Standard Time, UTC-06:00)
I guess I should expound on another reason why this is preferrable. The "switch" statement only works with strings, enumerations and numbers. A Dictionary can work with any type for a key. So you can look up based on an object instance, or even the specific Type of an object.
Chris
Wednesday, May 02, 2007 12:25:40 PM (Central Standard Time, UTC-06:00)
A question might be on timing or memory footprint, does this approach significantly slow down a process if the class containing the operations has multiple versions of itself created?

I have a class that handles one row of data from a database and processes the row via an external (read dynamic) set of rules. The rule names get *switched* off of to create a new row in an output dataset.

Hence this class gets created, literally thousand of times...if the DoD as you describe is implemented...does that slow it down in processing or cause a larger memory footprint?

If this was C++ and these were pointer to functions, I would guess that the damage would be negligibly ... but in C# who knows. <g>

I may do a test on my blog and report back (in the C# realm that is). Thanks for the article.
Monday, May 18, 2009 1:36:08 PM (Central Standard Time, UTC-06:00)
Hello everyone. Assuming either the Left Wing or the Right Wing gained control of the country, it would probably fly around in circles. Help me! Need information about: dual diagnosis treatment centers. I found only this - <a href="http://design.ru-deluxe.ru/">adobe photoshop 9 cs2 uroki</a>. Public health management corporation phmc is a nonprofit public health institute that builds healthier communities through partnerships with government. Alcohol rehab treatment programs alcohol rehab treatment programs. Thank you very much :o. Nyako from Tuvalu.
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):