Skip to content

Instantly share code, notes, and snippets.

@gregmajor
Created August 25, 2012 19:53
Show Gist options
  • Save gregmajor/3470208 to your computer and use it in GitHub Desktop.
Save gregmajor/3470208 to your computer and use it in GitHub Desktop.
If-Else State Machine
/*
* INTRO
* - Review a classic If/Else implementation
* - The myth of reducing cyclomatic complexity
*/
using System;
class Program
{
static void Main(string[] args)
{
var combinationLock = new CombinationLock();
combinationLock.Start();
Console.WriteLine(string.Format("Starting State: {0}", combinationLock.CurrentState));
combinationLock.EnterNumber(7);
Console.WriteLine(combinationLock.CurrentState);
combinationLock.EnterNumber(1);
Console.WriteLine(combinationLock.CurrentState);
combinationLock.EnterNumber(3);
Console.WriteLine(combinationLock.CurrentState);
Console.WriteLine(string.Format("Ending State: {0}", combinationLock.CurrentState));
}
}
public enum CombinationLockState
{
NoneRight,
OneRight,
TwoRight,
Open
}
public class CombinationLock
{
public CombinationLockState CurrentState { get; private set; }
public void EnterNumber(int number)
{
var nextState = this.CurrentState;
if (this.CurrentState == CombinationLockState.NoneRight)
{
if (number == 7)
{
nextState = CombinationLockState.OneRight;
}
}
else if (this.CurrentState == CombinationLockState.OneRight)
{
if (number == 1)
{
nextState = CombinationLockState.TwoRight;
}
else
{
nextState = CombinationLockState.NoneRight;
}
}
else if (this.CurrentState == CombinationLockState.TwoRight)
{
if (number == 3)
{
nextState = CombinationLockState.Open;
}
else
{
nextState = CombinationLockState.NoneRight;
}
}
else if (this.CurrentState == CombinationLockState.Open)
{
nextState = CombinationLockState.NoneRight;
}
this.CurrentState = nextState;
}
public void Start()
{
this.CurrentState = CombinationLockState.NoneRight;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment