I have a public readonly property that calculates its value based upon a couple of other private variables. I read from the calculated property a lot. The variables that are used in the calculation change very rarely. I currently have the getter of the readonly perform the calculation logic, but it makes more sense to me to push the new value into the property when the dependant variables change.
An example of my current code:
public class rectangle()
{
public rectangle(int height, int width)
{
_height = height;
_width = width;
}
public void resize(int heightOffset, int widthOffset)
{
_height += heightOffset;
_width += widthOffset;
}
private int _height;
private int _width;
public int area
{
get
{
return _height * _width;
}
}
}
The above code is overly simplified, but does a good job of showing what I mean. _height and _width can change, but they rarely ever do. The area property is read from a lot… I’d estimate that the _height/_width change once for every 100,000+ reads of the area property.
Now, if it was just multiplication, I wouldn’t be concerned… but the actual calcuations are complex and I’m seeing a lot of run time being sunk into repetitous superfluous calculations.
I know that I can do the following to fix it:
...
private int _height;
private int height
{
set
{
_height = value;
_area = _height * _width;
}
}
private int _width;
private int width
{
set
{
_width = value;
_area = _height * _width;
}
}
private int _area;
public int area
{
get
{
return _area;
}
}
...
The above code makes a lot more sense given my circumstances, but it just seems to me that there must be a better way to do this. I know that, given my first example, I could get rid of the properties and move the calculation logic to the resize() method… but in the real code it isn’t just one method that affects the private values. I don’t want to have to comb through my code to find every occurrence, and it doesn’t seem maintainable to do so.
Is the second method the way to go? I know it works, but something about it feels wrong. I think my concern is that it seems odd to have a private property storing it’s value into a private variable. I may be overthinking this.
Did you know property accessors can have access modifiers?
For example:
This works for auto-properties too:
UPDATE:
Ok, now you know about accessor access modifiers, what about this?
Goodbye, private fields!