The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
January 2001



This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.


pattern to eliminate switch statement

Posted by Tony Sintes on April 04, 2001 at 12:10 AM

The first step that you need to take is to reconsider your class structure. In a switch you normally case over some piece of data. Can you turn that data into an object.

Switch statements are a good indication that the object structure may be lacking (however, you cannot always avoid case).

Consider this switch:

void printDayOfTheWeek( int day_of_the_week ) {
switch (day_of_the_week)
case 1: System.out.println("Sunday");
case 2: System.out.println("Monday");
... etc

Do this instead:

void printDayOfTheWeek( Day day ) {
System.out.println(; // where day returns the day as a string

Data validation is one place where it is difficult (if not impossible) to remove a switch. However, in other places, you need to turn your data into objects.

In OO you don't want to ask your objects to give you data and then process that data. Instead, you want to ask an object to do something to its data. switches generally break from this way of thinking.

Check out Refactoring by Martin Fowler for an entire section about killing switches.

Tony Sintes

> I have lot of 'switch' statements which really
> clutter up the place and cause very inflexible class design.

> Is there a design pattern which eliminates the need for te switch statements ?

> thanks
> Pat


Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us