Tuesday, February 07, 2012

Property-local variables

Many variables are only ever required by a property, and should only be accessed or mutated by that property.  For example,
private Image _background;
public Image Background {
    get {
        return _background;
    }
    set {
        _background = value;
        Invalidate();
    }
}
The only place that should be using the _background field is the Background property, as writing to _background without calling Invalidate() would be a bug.  However, any other properties in the class this is in could do it without the compiler caring. This can be circumvented by wrapping _background in a class that would call Invalidate for us, but the amount of code necessary is greater.
Why not fix all of these issues by simply allowing fields that are local to properties? Allow fields to be created with the following syntax, which is currently illegal in C#:
public Image Background {
    Image _background;
    get {
        return _background;
    }
    set {
        _background = value;
        Invalidate();
    }
}
The main problem I see with this is the complexity that results in combination with inheritance.  If a get or set is overriden, does the override have access to the field?  I can't come up with a clear argument one way or the other, although I think the default should be No -- a property with its own field shouldn't let anyone bother the field.  Perhaps allowing it to be marked as protected and accessed from overrides would be okay, but I'm not sure about the consequences.

No comments:

Post a Comment