C# Object-Oriented – Passing a Serial Port Instance

cinterfacesobject-oriented

Background

I am thinking about designing a (GoF/behavioral) command-pattern interface. I may decide to call this thing ICommand. I am thinking that I would have some sort of a queue containing a bunch of command-interface objects. I would like to exercise the queue, calling the interface method Execute for each of the items in this queue as follows…

DequeuedItem.Execute(); // invoke the command-pattern

For every single item in the queue, until exhausting it.

The implementation for the concrete associated with the Execute may look like…

// concrete implementation of execute
public void Execute()
{
    mySerialPort.ReadExisting(); // read data from a serial port
}

From what I understand, using COM ports can be tricky when it comes to who actually owns the port.

Additionally, there are other reasons why I don't just declare the SerialPort inside of the concrete-implementation. Like… lots and lots of commands will need to use that same port (but not at the same time). So I will need to pass the serial port to the concrete implementing ICommand. This leads me into my question…

Question

Would an open serial port still function after I pass it to another object?

Even if it would work, are there other implications I need to be conscious of?

Best Answer

Passing the reference

Yes it would still work because you are only passing the reference and therefore it doesn't alter the referenced object (nor create a copy)

Responsibility for opening/closing

There are 3 possible cases:

Only one command uses the serial port. The serial port is completely encapsulated in the command and is opened at the beginning of the command and closed at the end.

At least 2 commands use the serial port and performance isn't a problem (you don't have timings to ensure). Each command has an instance of the serial port (pointing to the same COM port). Each command is responsible for opening/closing. Since the commands are executed sequentially (DequeuedItem) there's no conflict on the serial port.

At least 2 commands use the serial port but you can't afford to open/close the serial port for each command. The serial port has to be instancied a level higher and given to every commands that need it. The commands don't decide to open/close the serial port, they assume they receive an already open port and they shouldn't alter its state. The serial port could be opened at the moment a command requiring the serial port is added to the queue. The port could be closed when the queue finishes to execute the last command requiring the serial port.

Within these 3 cases, I think there is no bad solution. Each case is appropriate (or not) depending on the usage you make (sparsly, intensively, accurately, ...). The way you use the serial port seems fine to me.