Introduction

This article describes refactoring a switch statement in order to reduce Cyclomatic complexity.

Background

Many developers would have scratched their heads in order to keep their Cyclomatic complexity under 10. In some cases, it is really not possible at first site. In this article, I have provided a way to do that. Take the example of a Device State machine. You have a number of device states as below:

Since you have 14 states, you will end up having a Cyclomatic complexity more than 14. Here is the way to reduce this complexity to 1. Do the following changes in the above class DeviceController. Declare a Dictionary.

public DeviceController()
{
_deviceStateHandler.Add(DeviceStatesEnum.Active, new Action(SetDeviceStateToActive));
_deviceStateHandler.Add(DeviceStatesEnum.Equilibrating,
new Action(SetDeviceStateToEquilibrating));
_deviceStateHandler.Add(DeviceStatesEnum.Error, new Action(SetDeviceStateToError));
_deviceStateHandler.Add(DeviceStatesEnum.Inactive,
new Action(SetDeviceStateToInactive));
_deviceStateHandler.Add(DeviceStatesEnum.PowerUp, new Action(SetDeviceStateToPowerUp));
_deviceStateHandler.Add(DeviceStatesEnum.Ready, new Action(SetDeviceStateToReady));
_deviceStateHandler.Add(DeviceStatesEnum.Running, new Action(SetDeviceStateToRunning));
_deviceStateHandler.Add(DeviceStatesEnum.ShoutDown,
new Action(SetDeviceStateToShoutDown));
_deviceStateHandler.Add(DeviceStatesEnum.ShoutingDown,
new Action(SetDeviceStateToShoutingDown));
_deviceStateHandler.Add(DeviceStatesEnum.StartRunning,
new Action(SetDeviceStateToActive));
//TODO
//Create mapping for all the states
}

Comments and Discussions

same is the scenario, i want to refactor the switch statementbut my functions take 2 parameters and return bool.So the question is in this case how to pass the parameters to the functionand how to call it.

Although your sample may not be the best (as written in other comments), I think it's important that such switch cases have to be eliminated.Either with a problem specific solution (like you did it, however I'd prefer using an existing state machine implementation like the one in bbv.Common[^]) or with polymorphism.