• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 321
  • Last Modified:

Private Properties

I'm looking at a piece of code that was written a while ago by an experienced developer, and one thing I notice is that he has used private properties to access his private variables

i.e. He has public accessors to expose certain private variables to the outside world, but he also uses private accessors to expose them internally, so that he never directly reads or writes the private variable.

Is that good practice to do so, or is it an unnecessary layer of encapsulation? If so, what are the reasons?

The code itself is written in C#, but does have some unsafe code blocks as it accesses parts of the Windows API...don't know if that makes any difference?

Many thanks
Gerry
0
gamesmeister
Asked:
gamesmeister
1 Solution
 
Razzie_Commented:
Well it could be used for when you want to do something with the value before getting or setting it. But if that is not used, you could say it does not add anything.

That doesn't mean it useless though. Maybe the developer likes to work with properties. Also, an advantage could be that in the rare occassion you'd want to make a variable public it would be easier because you could simply change the accessor of the property. Or, maybe he likes it to make sure he doesn't accidently set the variable in a method. Leaving the set accessor could accomplish this.

Anyway, the extra overhead isn't really an issue :)
0
 
Bob LearnedCommented:
There is a generalized guidelines for fields and properties as highlighted here:

C# properties
http://www.csharp-station.com/Tutorials/Lesson10.aspx

For internal use, it is generally preferred to have fields:

  private int someProperty = 0;)

and then expose that field to the outside world with a property:

public int getSomeProperty()
    {
        return someProperty;
    }

    public void setSomeProperty(int propValue)
    {
        someProperty = propValue;
    }

Bob
0
 
gamesmeisterAuthor Commented:
Thanks for the responses.
0

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now