Hi, the summary of my question is "I have 2 classes which share a common interface, however the two classes have different behaviour with regard to their properties. One interface throws an exception if the parameter values are invalid the other updates its internal state to handle the invalid values. Is it okay for the two classes to share the same interface or should two interfaces be defined to indicate to the developer that the two have different behaviours?"
I'll try to clarify with some code. I have the interface defind below.
public interface IStationDictionary { bool this[string stationId] { get; set; } }
And a class that implements the interface, this class is used to set the output port on a digital IO board.
public class DigitalStationAdapter : IStationDictionary { public bool this[string stationId] { get { return ports[stationId].Value; } set { ports[stationId].Value = value; } } public void AddDigitalStation(string stationId, DigitalIoPort port) { ports.Add(stationId, port); } private IDictionary<string, DigitalIoPort> ports = new Dictionary<string, DigitalIoPort>(); }
I also have a classes that records which stations have had values changed so that those changes can be propegated to the digital IO.
public class StationTransitions : IStationDictionary { public bool this[string stationId] { get { bool result = false; if(changes.ContainsKey(stationId)) result = changes[stationId]; return result; } set { if(!changes.ContainsKey(stationId)) changes.Add(stationId, value); else changes[stationId] = value; } } public IDictionary GetChanges() { IDictionary<string, bool> result = changes; changes = new Dictionary<string, bool> return result; } private IDictionary<string, bool> changes = new Dictionary<string, bool>(); }
So, while both classes implement the same interface DigitalStationAdapter will throw a KeyNotFoundException if you try to access the indexer with a stationId not in the dictionary. Whereas, StationTransitions will succeed, i.e. different behaviour. Is this okay, I thought that interfaces are used to define behaviour as well as structure?
Keith.