I have created a library class CircuitController that communicates with a control circuit via serial port.
public class CircuitController
{
// Enumerations.
public enum Sensors { Sensor1, Sensor2, ..., Sensor15 };
...
// Fields.
private SerialPort serialPort; // Set in constructor.
private Dictionary<Sensors, Sensor> activeSensorCollection;
...
// Properties.
public Dictionary<Sensors, Sensor> ActiveSensors
{ get { return this.activeSensorCollection; } }
// Methods.
public void SetSensorUnits(Sensors sensor, String sensorUnits)
{
// Creates serial command based off parameters, sends, receives, processes.
}
...
// Constructors.
public CircuitController(...)
{
... // Set CircuitController fields including nested classes.
Sensor sensor1 = new Sensor(a,b,c,d,this); // Link sensor to this controller instance.
... // Add sensors to dictionary.
}
// Nested Classes.
public class Sensor
{
// Fields.
private CircuitController controller;
private String units;
private Sensors sensorNumber;
...
// Properties.
public String Units
{
get
{
return this.controller.GetSensorUnits(this.sensorNumber);
}
set
{
this.controller.SetSensorUnits(this.sensorNumber, value);
}
}
...
}
So here is my questions: Is it OK to allow the user to get/set the sensor settings through properties even though an exception may be thrown (e.g. serial communication error)?
String sensor2Units = circuitControllerInstance.ActiveSensors[Sensor2].Units'
circuitControllerInstance.ActiveSensors[Sensor1].Units = "mm";
I find this much clearer than…
String sensor2Units = circuitControllerInstance.GetSensorUnits(Sensors.Sensor2);
circuitControllerInstance.SetSensorUnits(Sensors.Sensor1, "mm");
Please note that these are simplified examples, some of the Get/Set methods have up to 5 parameters which would be a hassle to repeatedly type out. :/
I would tend to avoid actually doing anything when a property is set. Instead let all the properties be set in memory, then add a “Save” method that will “save” the properties to the serial device.