I have a class UnitInfo which represents a collection of unit information with methods to get the unit information in a structured way, such as a specific encoding, etc. This unit info consists of information which must be read from the unit via serial port communication. The constructor of the class is given the serial number, which cannot be queried from the unit, and an instance serial communication interface, which it then uses to query the unit for the information:
public class UnitInfo {
public int SerialNumber { get; }
public int InternalMemorySize { get; }
// And more properties...
public UnitInfo(ISerialCom serialCom, int serialNumber) {
SerialNumber = serialNumber;
InternalMemorySize = serialCom.GetInternalMemorySize();
// More serial communication to set more properties
}
// Get methods to retrieve all the unit information in a specific encoding
// i.e a collection of bytes.
}
From my browsing SO and Google, I understand that it is usually okay to do work in a constructor, but I've yet to find an example of performing communcation via serial, GPIB, etc. in a constructor. I'm also thinking this may be a violation of the Dependency Injection principle as the class is dependent upon some implementation of an interface to initialize itself; is it better to pass all of the unit information to the class?
ISerialCom, which is presumably an interface. So you are injecting its dependency, rather than it being tightly coupled to that dependency by eg performing anew SerialCom()itself.