3

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?

kmote
  • 16,095
  • 11
  • 68
  • 91
  • If it is so important then it is worth to be unit tested – Sir Rufo Jun 08 '17 at 14:18
  • 2
    *"to prevent the class developer from making this mistake"* - that's overkill, seriously. If person modifying that class, need help like this, then rather don't let this person modify anything. Comments should suffice. From other side you can give this field *dedicated* name: `_doNotModifyMePlx`. – Sinatr Jun 08 '17 at 14:28

1 Answers1

2

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;
     }
}
Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
  • 1
    Duplicate of the answer on this question: https://stackoverflow.com/a/3265833/993547 :) Two minds thinking the same. – Patrick Hofman Jun 08 '17 at 14:17
  • This solution gives nothing. One month later someone will try to add new functionality to the base class, and problem will back. – apocalypse Jun 08 '17 at 14:22
  • I mean, if someone has access to your codebase, there's only so many failsafes you can put in. If they want to destroy your code they can. – Jonesopolis Jun 08 '17 at 14:27