I was wondering, what is good practice:
private int value;
public int Value { get { return this.value; } }
private int DoSomething()
{
return this.Value + 1;
//OR
return this.value + 1;
}
So, the question is about how you should treat your class variables. Should you access them through your properties or just direct?
In this case, it doesn't matter so much, but in cases where you're using lazy loaded variables it would matter and you'd access through your property. For instance:
private Myobject _value;
public Myobject Value
{
get
{
if (_value == null) _value = new MyObject();
return _value;
}
}
private MyObject DoSomething();
{
//If you access _value here, it might be null...
//so you should access it through the property:
return Value;
}
In a case where your method would fail by calling the field directly, you either handle it properly, or you access it by the cleaner method - via your property.
It all comes down to the architecture of your application and for that you have to ask the question: What makes the most sense from a maintenance perspective?
I would have to say that if the field is initialized properly and it doesn't cause you a headache to access it directly, then access it directly. If it causes extra work (and thus extra maintenance), then reference the property.
Like with anything else, weigh up the pros and cons. Use your own common sense - standards wars are a ridiculous distraction. Unless they provide you with arguments you haven't already thought of yourself, don't waste your breath fighting with them. If you have a valid reason to choose whichever path you choose, then that path is the right one - it comes down to the designer's prerogative.
My thoughts on pros and cons are this:
Going with property:
Going with the field:
So I guess my approach would be to use the property unless I needed to write to the value directly, in which case, I'd go with the field - as my property is read-only and thus can't be written to.
That's just me though - your property may be read/write and you may decide from a design standpoint that accessing the field directly is okay - and that is okay too.
The trick is always do things for a reason, don't do things blindly just because.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With