Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide the backing field from the rest of the class [duplicate]

Is there any way to enforce the rest of my class to access the property setter rather than the backing field? Consider the following clumsy code:

public class Brittle
{
    private string _somethingWorthProtecting;
    public string SomethingWorthProtecting
    {
        get { return _somethingWorthProtecting; }
        set
        {
            _somethingWorthProtecting = value;
            ReallyNeedToDoThisEverTimeTheValueChanges();
        }
    }

    public void OhDearWhatWasIThinking()
    {
        _somethingWorthProtecting = "Shooting myself in the foot here, aren't I?";
    }
}

As far as I know, C# does not provide any mechanism to prevent the class developer from making this mistake. (Auto-properties are clearly not an option in this situation.) Is there a design pattern or practice that can help safeguard against such inadvertant end-arounds?

like image 515
kmote Avatar asked Dec 12 '25 04:12

kmote


1 Answers

you can move that logic to an abstract base class:

public abstract class Brittle
{
    private string _somethingWorthProtecting;
    public string SomethingWorthProtecting 
    {
        get { return _somethingWorthProtecting; }
        set
        {
            _somethingWorthProtecting = value;
            ReallyNeedToDoThisEverTimeTheValueChanges();
        }
    }

    //.....
}

then you can be sure no one will instantiate this class, and derived classes will not be able to access the private field.

public class BrittleDerived : Brittle
{
     public void DoSomething() 
     {
        // cannot access _somethingWorthProtecting;
     }
}
like image 159
Jonesopolis Avatar answered Dec 13 '25 22:12

Jonesopolis