• Home >>  Java >>  Programming Tips
  • reducing code complexity on switch-blocks


  • Rating : Excellent[0]   Very Good[0]   Average[0]   Below Average[0]   Poor[0]
  • Pub Date: 10/14/2008
  • admin [ View Profile ]

  • Abstract
  • A switch-block becomes complex very easily. All code is placed in one method and parts of it are used multiple times. In a lot of cases, a switch-block is based on an enum. Next to that, it's not possible to use a fall-through in C#. The only way to go from case to case is the use of the goto statement, which isn't a good idea when reducing complexity. Although I've written the examples in C#, it wouldn't be hard to apply the principles......

  • Introduction
  •  Sponsored Links
  • introduction

    a switch-block becomes complex very easily. all code is placed in one method and parts of it are used multiple times. in a lot of cases, a switch-block is based on an <code>enumcode>. next to that, it's not possible to use a fall-through in c#. the only way to go from case to case is the use of the <code>gotocode> statement, which isn't a good idea when reducing complexity. although i've written the examples in c#, it wouldn't be hard to apply the principles to other languages.

    a solution

    a nice solution to get rid of large switch constructions is the use of a <code>dictionary<enum,delegate>code>. this way every element of the <code>enum code>can be attached to a method. it is possible to call the right method for every <code>enum code>possible. because every <code>enum code>has its own method, it's very easy to use this construction in a testdriven environment. another nice thing is that it's no problem to call one method from another. let me explain a little further with an example and some pseudo code. imagine a program that prepares food. this part contains the recipes.

    let us start with the following <code>enumcode>:

    enum food{
        apple,
        applepie,
        applejuice,
        pizza
    }

    it's not hard to imagine that all of the foods need a specific preparation, but that some actions need to be done for different foods, like peeling an apple or baking in the oven.

    to add the preparations to the <code>dictionary<enum, delegate>code>, we first need to define a <code>delegate code>method:

    delegate bool preperation();

    now we need to define the actual preparation methods for every item of the <code>enumcode>, making sure they're declared the same way as the <code>delegatecode>, thus the same parameters and return value. the method returns a boolean when preparation is successful.

    in this example, the methods may look something like this:

    bool peelapple()
    {
    	// code to remove peel
    	return true;
    }
    bool bakepie()
    {
    	preheatoven(180.0);
    	peelapple();
    	createpie();
    	while(!donebaking())
    		bake();
    	return true;
    }
    bool makeapplejuice()
    {
    	peelapple();
    	juicify();
    	return true;
    }
    bool bakepizza()
    {
    	preheatoven(160.0);
    	createpizza();
    	while(!donebaking())
    		bake();
    	return true;
    }

    notice that <code>bakepie()code> and <code>makeapplejuice()code> both call the method <code>peelapple()code>. this is not possible in a <code>switch code>– case constructor, unless you call the methods from each case.

    now all that's left is to create and initialize the <code>dictionarycode>.

    dictionary foodpreperation;
    ..
    foodpreperation = new dictionary<food, preperation>();
    foodpreperation.add(food.apple, new preperation(peelapple));
    foodpreperation.add(food.applepie, new preperation(bakepie));
    foodpreperation.add(food.applejuice, new preperation(makeapplejuice));
    foodpreperation.add(food.applepizza, new preperation(bakepizza));

    calling the methods is done by:

    food foodofchoice = food.applepie;
    foodpreperation[foodofchoice]();

    in the last code snippet, the method that goes with <code>food.applepiecode> is executed.

    history

    • 07 oct 2008 - initial upload
  • RATE THIS ARTICLE :
  •  
    • Latest Comments:
      • Add a comment
      • Title:
      • Comment
      •  
    Other popular Programming Tips articles:
    • VSS: protocol handler for Visual SourceSafe

      Imagine that you could open a document in a Visual SourceSafe database with one mouse click.

    • How to use google and other tips for finding programming help

      Code Project is a wonderful resource. Certainly, my career as a developer is built on the help I got here learning MFC in late 1999. However, it's increasingly the case that a lot of the questions on our forums are easily answered by a simple google search, so I'm writing this article to explain how

    • broadcast a message to multiple instances of an application

      This application describes how to broadcast a message to multiple instance of an application using SendMessageNotify API. DetailsFollow the following steps to broadcast message :-Register the message function and get its id using RegisterWindowMessageAPI. This function will return a unique id for th

    • about rss

      Want more traffic? Searching for an easy way to distribute your news? You need an RSS news feed. Thousands of web sites today use RSS as a "what's new" mechanism to drive traffic their way. RSS provides an easy way to monitor fresh content. RSS feeds highlight new material so that you don'

    • Developing applications that always decease gracefully.

      It is always a dream for every programmer under the sun, to write programs that never smash. So this article presents some guidelines in trapping exceptions which can kill applications, and thereby ensuring the graceful exit of a program. I have included some code snippets that show how to trap exce

    • unit test utility: restoring database state after each unit test execution

      Need: Lets start with an example, suppose we are writing unit tests for following two cases: GetCustomersByIdGreaterThan() AddCustomer() Initial state of database is like We run first unit test case for GetCustomersByIdGreaterThan()[Test]public void CanGetCustomersByIdGreaterThan(){const int CUSTOME

    • complexconverter - make configuration still more flexible

      Normal|0; 0; 765; 321|2|Knoten0|2|Knoten1|0|False|Knoten2|3|Knoten4|0|False|Knoten5|0|False|Knoten6|0|False|False|True|Knoten7|2|Knoten8|0|False|Knoten9|0|False|False|90|90|90|90|2|4|01|02|03|04|4|11|12|13|14Inside ComplexConverterComplexConverter has a problem, when set up, or conversion-code is ch

    • driving or automating gui applications

      Sometimes you want or need to control (or automate the use of) an application but the application provides no automation API (command line interface or CLI, COM component, .NET API DLL, web service, etc.), so what do you do? You're left with (graphical) user interface (GUI) automation. Although, in

    • unit testing starter - vs.net 2008

      Unit Testing starter - VS.NET 2008 Hi Everybody,As you know, VS.NET 2008 comes with unit testing integrated within. To start with a testdriven approach, we need to understand how unit testing works in VS.NET 2008. Many of usmight be using already available tools / frameworks for this, viz - NUnit (M

    • cost reduced swap

      void main() { int i=10,j=20; j=i+j-(i=j); } Here the two variables are swapped in a single statement . The cost is reduced than the known swapping methods. Temporary variables are not used.addition and subtraction only.can be used for any data types and this is efficient than the normal methods.time

    About Us |Contact us |Site Map |Csharp |Visual C / C++ |Visual basic |Java |SQL |Linux / Unix |Ajax
    ©2007-2018 CodeCoolest.com. Ptolive.cn Asp.net source code All Rights Reserved.