Click here to Skip to main content
Licence CPOL
First Posted 7 Oct 2008
Views 52,655
Bookmarked 91 times

Reducing Code Complexity on Switch-blocks

By Timmy Kokke | 7 Oct 2008
Using a Dictionary instead of a switch-case construction to reduce complexity and increase testability

1
1 vote, 1.9%
2
4 votes, 7.7%
3
11 votes, 21.2%
4
36 votes, 69.2%
5
4.79/5 - 52 votes
5 removed
μ 4.54, σa 1.27 [?]

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 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 to other languages.

A Solution

A nice solution to get rid of large switch constructions is the use of a Dictionary<enum,delegate>. This way every element of the enum can be attached to a method. It is possible to call the right method for every enum possible. Because every enum 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 enum:

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 Dictionary<enum, delegate>, we first need to define a delegate method:

delegate bool Preperation();

Now we need to define the actual preparation methods for every item of the enum, making sure they're declared the same way as the delegate, 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 BakePie() and MakeAppleJuice() both call the method PeelApple(). This is not possible in a switch – case constructor, unless you call the methods from each case.

Now all that's left is to create and initialize the Dictionary.

Dictionary<food, /> 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.Pizza, 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 food.ApplePie is executed.

History

  • 07 Oct 2008 - Initial upload

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Timmy Kokke

Software Developer
UNIT4 Internet Solutions
Netherlands Netherlands

Member

Follow on Twitter Follow on Twitter
MVP Expression Blend. Founder of Sixin.nl the dutch Silverlight and Expression Usergroup. Silverlight developer. Writer. Composer. Musician.
 
Twitter
@Sorskoot
 
Awards / Honers
• October 2010: Awarded Microsoft Expression Blend MVP
• June 2009: Second Place in the WinPHP challenge
• February 2009: Runner-up in de Mix09 10k Challenge
• June 2008: Winner of the Microsoft expression development contest at www.dekickoff.nl
 
Bio
I started programming, I believe, around 1992, when my father had bought our first home computer. I used GWBasic at that time. After using QBasic and Pascal for a few years I started to learn C/C++ in 1996. I went to the ICT Academy in 1997 and finnished it in 2002. Until December 2007 I worked as a 3D specialist. Besides modelling I worked on different development projects like a 3D based Scheduler and different simultion tools in C# and Java. Today I work as a Silverlight developer at an UNIT4 Internet Solutions in the Netherlands.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralMy vote of 5 PinmemberManuel_Perez_II22:02 26 Jul '11  
GeneralMy vote of 5 PinmemberEklavya Mirani3:58 17 Jul '11  
GeneralMy vote of 5 PinmemberSAKryukov9:14 30 Nov '10  
GeneralNice PinmemberThanos Papathanasiou4:05 8 Feb '10  
GeneralMore improvements PinmemberSAKryukov8:05 11 Jan '10  
GeneralQuite correct approach! Long switch statements are for loosers. PinmemberSAKryukov7:44 11 Jan '10  
Generalswitch PinmemberSlava Khristich7:30 6 Jan '09  
GeneralRe: switch PinmemberDonsw14:37 26 Jan '09  
GeneralSpeed of this versus switch-blocks Pinmemberwwahammy2:33 27 Oct '08  
GeneralRe: Speed of this versus switch-blocks PinmemberTimmy Kokke23:18 29 Oct '08  
GeneralRe: Speed of this versus switch-blocks PinmemberSAKryukov8:28 11 Jan '10  
GeneralThats a Good Solution ! PinmemberSamer Abu Rabie12:42 24 Oct '08  
GeneralGood One PinmemberSneha B Patel0:30 15 Oct '08  
GeneralI've done the same kind of thing but used reflection to build the dictionary... PinmemberMember 218767816:56 8 Oct '08  
GeneralRe: I've done the same kind of thing but used reflection to build the dictionary... PinmemberTimmy Kokke21:27 8 Oct '08  
GeneralRe: I've done the same kind of thing but used reflection to build the dictionary... PinmemberMember 218767814:36 10 Oct '08  
GeneralRe: I've done the same kind of thing but used reflection to build the dictionary... PinmemberMember 218767814:31 14 Oct '08  
GeneralI've done this. PinmemberJamie Nordmeyer5:30 8 Oct '08  
GeneralRe: I've done this. PinmemberTimmy Kokke21:23 8 Oct '08  
GeneralRe: I've done this. PinmemberJamie Nordmeyer5:54 9 Oct '08  
GeneralRe: I've done this. PinmemberPalisade11:19 12 Jul '11  
GeneralNice idea PinmemberLeeland Clay4:05 8 Oct '08  
GeneralA design pattern alternative Pinmemberervegter3:10 8 Oct '08  
GeneralRe: A design pattern alternative PinmemberTimmy Kokke3:16 8 Oct '08  
GeneralRe: A design pattern alternative Pinmemberzenwalker198519:18 1 Oct '11  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120209.1 | Last Updated 7 Oct 2008
Article Copyright 2008 by Timmy Kokke
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid