Search code examples
c#design-patternsencapsulation

Update class from another class, encapsulation issue


How must I update a class, which must be updated only from another specific class?

In the following example encapsulation is broken, because Sensor can be updated from any other class, not only from Device. Am I right?

class Device
{
    public IEnumerable<Sensor> Sensors { get; private set; }

    void SomeInternalCall(int sensorId, int signal)
    {
        Sensors.First(s => s.Id == sensorId).Update(signal);
    }

}

class Sensor
{
    public int Id { get; private set; }

    public event Action<int> OnSignal;

    public void Update(int signal)
    {
        if (OnSignal != null) OnSignal(signal);
    }
}

class SensorUser
{
    public SensorUser(Sensor s)
    {
        s.OnSignal += SignalHandler;
    }

    void SignalHandler(int signal)
    {
        // ...
    }
}

Solution

  • You can create an interface that provides read-only access and give it to SensorUser, while having a collection of Sensor instances in Device.

    interface ISensor
    {
        int Id { get;  }    
        event Action<int> OnSignal;
    }
    
    class Sensor : ISensor
    {
        public int Id { get; private set; }    
        public event Action<int> OnSignal;
    
        public void Update(int signal)
        {
            if (OnSignal != null) OnSignal(signal);
        }
    }
    
    class SensorUser
    {
        public SensorUser(ISensor s)
        {
            s.OnSignal += SignalHandler;
        }    
    }