I have a winform tool that interfaces with hardware using a serial port.
The serial port is used to send commands to the the hardware, which will acknowledge the commands and sometimes return data.
To accomplish a task, several commands need to be sent to the hardware in a defined order.
I have successfully implemented the tool using a switch statement to control the sending of the commands. However, while this works, I can't help thinking that there is a better, more OO way of doing this - is there?
Current implementation is below:
Each case is a command that needs sending to the hardware. Send method is passed a method to invoke and the ID of next step - which will be returned if command sent successfully.
etc.
MessageID nextStep = MessageID.IMS;
while (nextStep != MessageID.Stop)
{
switch (nextStep)
{
case MessageID.ISS:
nextStep = Send( new ISS_StartSession(), MessageID.IE386);
RaiseProgressEvent(10); //percentage complete
break;
case MessageID.IE386:
nextStep = Send( new IE386_SetDirection(Direction.BOTH), MessageID.IE378);
RaiseProgressEvent(20);
break;
//etc
case MessageID.Error:
HandleError(); //abort task if necessary
break;
}
}
Is there a better way to do this..?
Is there a well known design pattern I should look at?
Looks like a State Machine. There are lots of resources on the net about them. Have a look.
http://en.wikipedia.org/wiki/Abstract_state_machines
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With