Search code examples
c#oopdesign-patternspropertiesencapsulation

Should custom logic for a property go in the setter or the getter?


I have a public boolean property which is backed by a private field. The situation is such that if some condition X is true, then the property should always be true. However, if the condition X is false, then the property can either be true or false, as specified when the object is initialized.

I'm not sure if I should check for the condition X in the getter or the setter.

In other words,

private bool _myProperty;
public bool MyProperty
{
    get { return _myProperty; }
    set
    {
        if (condition X)
            _myProperty = true;
        else
            _myProperty = value;
    }
}

or

private bool _myProperty;
public bool MyProperty
{
    get 
    {
        if (condition X)
            return true;
        else 
            return _myProperty; 
    }
    set { _myProperty = value; }
}

I'm sure this is dependent on more details of the situation. Currently, the property is only ever accessed inside of the class in the OnStartup() method.

I see that the danger with the second solution (checking in the getter) would be that the private field and the public property can get out of sync. So I'm thinking the first solution, checking in the setter, is the way to go?

EDIT: Since this keeps coming up, condition X is a user permissions thing. It cannot change within a session.

EDIT: The answers and comments made me think of this:

private bool _myProperty = conditionX;
public bool MyProperty
{
    get { return _myProperty; }
    set 
    {
        if (_myProperty == false)
            _myProperty = value;
    }
}

Solution

  • I think, in a majority of cases like this, you'll probably want to put your logic in the getter.

    If condition X can change whether it's true or false at any time, the value of your property should update to reflect this no matter when it's read, then you should put you logic in the getter.

    The other option will only update the property when it's set, so if you set the property, and then condition X changes at some point, followed by a read of your property, then the value of the property that is returned does not truly reflect the state of condition X. However, there might be some cases where you want this behavior.