views:

264

answers:

10

Hi,

When inside a class you have a private fiels and expose that field on a public property, which one should I use from inside the class?

Below you is an example on what I am trying to find out. Should manioulate the Private Field _Counter or the Property Counter?

Public Class Test

Private _Counter As Integer

Public Property Counter() As Integer
    Get
        Return _Counter
    End Get
    Set(ByVal value As Integer)
        _Counter = value
    End Set
End Property

Private Sub Dosomething()

    'What is the best practice?
    'Direct access to private field or property?

    'On SET
    _Counter += 1
    'OR
    Me.Counter += 1

    'On Get
    Console.WriteLine(_Counter)
    Console.WriteLine(Me.Counter)

End Sub

End Class

Thanks in advance for the help. Edu

A: 

I prefer to use the property whenever possible. This gives you the flexibility in the future to modify what the property returns/sets without having to go through and find all the locations that were using the private variable.

Andy White
A: 

Use the private field because you are not doing something in specific in the setter.

I would also recommend to remove the property-setter, this way you force the state of the counter to be set by the given method DoSomething()

Patrick Peters
A: 

Depending on the situation, it may be preferable to allow the direct modification of a field on a class only privately, and or through some method which associates semantics with the modification. This way it becomes easier to reason about this class and that particular value, since you can be certain that its modified only in a certain way. Moreover, at some point, an action such as incrementing and int may have additional required consequences at which point it makes more sense to expose access to it through methods.

eulerfx
+1  A: 

IMO you should be using the Property accessor whenever possible. This is because you don't have to worry about any internal logic that might be available when you have an a property.

A good example of where this happens is in the code behind in a Linq DataContext.

check this out...

[Column(Storage="_ReviewType", DbType="TinyInt NOT NULL")]
public byte ReviewType
{
    get
    {
        return this._ReviewType;
    }
    set
    {
        if ((this._ReviewType != value))
        {
            this.OnReviewTypeChanging(value);
            this.SendPropertyChanging();
            this._ReviewType = value;
            this.SendPropertyChanged("ReviewType");
            this.OnReviewTypeChanged();
        }
    }
}

Notice all that logic in the 'setter'?

This is why it's important to start getting into the practice of calling your Properties instead of fields, IMO.

Pure.Krome
@Pure: did you notice that there isn't any logic in the given example? So there is no need to use the public property. It is like you are in a house and you want to flush to toilet, you go outside, open the door again and open the toilet door to flush to toilet.
Patrick Peters
No logic? Um. OK -> so when i set the review type (via Property), it then fires off some events, if those events are not null. That's logic, to me. If he got in the habit of setting the field, instead of the property, then the events wouldn't be fired .. which is pretty serious stuff IMO.
Pure.Krome
Thanks for the reply and I totally see where you are comming from. After reading all the replies what caught my attention was "if you need to attach some special logic in the public accessor, chances are that the logic may not be the same for internal access.".I am leaning towards set the standard to access directly the private field, and only access the accessor if its implementation code is really needed. (They should have a new scope for variables that can only be accessed by its accessor. :)
Edu
A: 

I always use the property accessors, because the I am safe in case I add logic in the getter or setter in the future, knowing for sure that no code bypasses it.

Fredrik Mörk
A: 

If you are worried about the performance overhead of calling property accessors when they just go directly to the field, don't. Most compilers will inline this sort of thing, giving you effectively the same performance. At least, you're pretty unlikely to need the extra nanoseconds of time you might gain by going directly to the field.

It's better to stick with property accessors because a) you can be very consistent in all of your code which makes it more maintainble and b) you get the benefits pointed out by others here.

Also, I don't usually add the Me. (or this.) keywords, unless there's a scope problem (which I try to avoid by choosing my identifiers carefully). I don't get confused by this because my functions and subs are never so long that I'm not sure whether I am working with a local (stack-based) variable or a member of the class. When they get too long to tell easily, I refactor.

Alan McBee
I see your point but I'm really getting the impression that on this case what is important is to be consisten in your code. I allways coded accessing the private _Fields directly and when accessing an accessor I would allways use the Me. to leave very clear that I am accessing a property. Thanks for the input
Edu
+1  A: 

In my opinion, using a public accessor internally is over-encapsulation: it blurs the code. With such an approach, otherwise simple operations invoke accessors that may contain more complex logic, so it's harder to analyze the code of the operations.

In my programming experience, I've rarely had a situation when it would help much. Instead, I prefer to access fields directly, and only if it's really needed, to abstract the access by creating a private accessor, which can be used by both the public accessor and other functions. The rationale is that if you need to attach some special logic in the public accessor, chances are that the logic may not be the same for internal access.

Note also that most modern IDEs (like Eclipse) allow to see immediately all references to a private field, and to refactor the code to use a function instead of a direct access.

Bartosz Klimek
Thanks a lot for your input. I got from your answer a very important decision point: "if you need to attach some special logic in the public accessor, chances are that the logic may not be the same for internal access."
Edu
+2  A: 

Thank you all for the answers and suggestions.

After considering all the suggestions here plus other researches it is my impression that for this situation on Private Field versus Assessor it is more of a personal choice. So basically the most important is that no matter what you choose be consistent.

That said; my personal rule is leaning towards this:

1) Access your private fields directly.

2) If accessing accessors use the keyword ME. to improve readability

3) Use the accessor only if it implements vital logic logic that also applies to private access. This way you know that if you are using the accessor it is because there is “something else to it”

4) Avoid using Protected Fields. Derived classes should always use the accessor, never direct access to the field.

Let me know what you think.

SideNote: After this I think we are missing a new scope for the class level fields. A keyword like “Restricted” where this field could only be accessed from its getter/setter. This way you always access directly the private fields, but if you need to make sure certain field can only be accessed by its accessor that you change the Private to Restricted. (how about “Restricted , RestrictedRead and RestrictedWrite”?)

Edu
Question: How do u know if an Accessor has any vital logic? U might remember today .. but in 5 months .. u might forget. U're still mixing and matching. Always go for the accessor. Secondly, using Automatic Properties (http://weblogs.asp.net/dwahlin/archive/2007/12/04/c-3-0-features-automatic-properties.aspx) gives you the best of both worlds, which is what u are doing. Stick to accessors IMO.
Pure.Krome
Sick to 'automatic properties' IMO, is what i ment to say. If a property needs more logic, then go for it :) otherwise it's an 'automatic property'.
Pure.Krome
A: 

Original poster is EXACTLY correct.

1) Access your private fields directly.

  • Makes refactoring easier.

2) If accessing accessors use the keyword ME. to improve readability

  • explicitly listing scope requires less thinking by reader

3) Use the accessor only if it implements vital logic logic that also applies to private access. This way you know that if you are using the accessor it is because there is “something else to it”

  • this is the only reason to violate rule #1.

4) Avoid using Protected Fields. Derived classes should always use the accessor, never direct access to the field.

A: 

Alan says he will use privates unless someone says the iphone only comes in black

bob