Properties vs. Public Variables

Just checked this in the “Framework Design Guidelines”, and it says “no public or protected instance fields”. It then notes:

  • Trivial properties can often be inlined by the JITer (so no performance overhead)
  • Cannot change fields to properties without breaking the interface (whether used directly, or via reflection).

While these are aimed at framework developers, it would seem there is little loss (especially since VS2k5 will do the property generation for you), and several benefits in always using properties.

WTF?

“public property string IOnlyWriteTrivialObjects”?

Developer: So, how do you create a property in C#?

ADDGuru: Well, you use “public property string memberVariable”

Developer: So what does that do?

ADDGuru: Well, it allows you to get and set a variable.

Developer: So what if you just want a setter or just a getter?

ADDGuru: Um, well, you use a whole other syntax. That maybe you should have used in the first place so that you could make these changes easily.

Developer: How about if I want to add some logic to the getter/setters?

ADDGuru: Um, well, you use a whole other syntax. That maybe you should have used in the first place so that you could make these changes easily.

Developer: Oh, I see. So that first syntax is pretty well useless.

ADDGuru: Yup.

WTF #2

Am I the only person here who actually creates business domain specific types, and actually sometimes needs only getters? Am I the only person who uses private variables?

“What’s the difference between a variable and a property?”

What the hell? Were you smoking crack when you wrote this, or have you literally never created a type that needed private variables? Or even a trivial bit of logic in a property? I know you’ve written about how OO design is so “hard”, and how you prefer DataSets (shudder), but my God.

public property string IOnlyWriteTrivialObjects"

In case you missed the last 50 comments, we need this because .NET has a crazy, nonsensical division between variables and properties. I’ll recap for you:

a) You can’t reflect on them the same way
b) Changing from variable to property (or vice-versa) breaks binary compatibility
c) You can only databind to a property

have you literally never created a type that needed private variables?

Have you literally never created a type that needed private properties?

I know you’ve written about how OO design is so “hard”

Not so much “hard” as “frequently abused”.

“While these are aimed at framework developers, it would seem there is little loss (especially since VS2k5 will do the property generation for you), and several benefits in always using properties.”

I don’t think runtime performance or automation was ever the issue. But readability is.

How can a guru (as inn ADDGuru) so miserably interpret these posts to promote three syntaxes?

To the guru, which fails to earn the title, we’d like two property syntaxes:

  1. The old one. Use this when syntax #2 is not up to it.
  2. A one liner to create the simple, passthrough property which happens to be used a lot.

We could extend the syntax a little:

public readonly property int Number;
public writeonly property int Number;

But the latter would be just cosmetic. If we can write to the property, what’s the harm to be able to read it?

some notes…

  • no good reason not to use a mutator/accessor…keeping it simple in my mind means being as consistent as possible. That prevents you from giving any thought to using get/set methods, or not.
  • performance should not be a concern…simple mutator/accessors should be inlined. Of course, there are exceptions and other kinds of conventions like in C unix programming with structs.
  • as a matter of style, using getters and setters and avoiding local variables is also a way of making things very clean and minimizing mistakes.
  • I don’t think adding “m_” is always right these days. Use an IDE with proper semantic highlighting. =)

ok, let me add something…

properties/public variables should be fine as long as it is not an externally-facing struct…

used internally a public-variable-struct object is very nice…

On naming standards, I learnt C# on the back of the VS2005 beta - which meant I got to see the updated FxCop in there, which means I learnt that:

int importantData; // was the field
and
public int ImportantData {…} // was the property

so all this _importantData stuff seemed fairly turgid to me when I first saw it. And, I am another one who uses all-caps’n’underscores for consts.

It seemed to me that the intention behind some of the MS naming standards was accounting for the fact that the dev environment allowed for much visual feedback on what something was, whereas in the days of C we had our monochrome text editors and that was it.

I’m therefore a little surprised that no-one seems to have said:
"I want my constants to be simply RED, and I want my static readonly’s to be DEEP PURPLE, lest I forget I can not assign to them"
Don’t most people code .Net in IDE’s that understand the context (as opposed to text editors that can only do simple syntax colouring?)

Whichever way, part of the purpose of a naming standard is to help you read and understand the code; we tend to give constants a different naming scheme so that we can SEE and FEEL they are constants; the fact the compiler won’t let us assign to them is irrelevant, we need to understand this before that stage.

Nij

screaming constants help me know quickly what is a constant – and all I’m looking for here is less head scratching while coding.

“Name” and “name” coders need to be electrocuted or something. But in their defense it’s not all their fault, but rather those who invented case sensitive languages.

Coding a public variable as a property, while overkill many times, at least gives you the choice of later adding some intelligence or safety net logic to the value returned (for example) while not breaking anything.

My preferred coding style is:

const int _DefaultName = “John”;
int _name;

public int Name
{
get { return _name; }
set { _name = value; }
}

This bumps all of the class members to the top of the autocomplete list, and makes it easy to distinguish between properties, variables and consts without resorting to ALLCAPS or too many extra characters.

I think we can safely conclude when it comes to naming conventions, there is no right and wrong. I don’t personally see the added value using UPPER_CASING, but again, it could be that I am just not used it.

I proposed a feature request to Microsoft: To move the instance field inside of the property block. The intention is to secure all code to use the property, also the instance itself. There are some circumstances where accessing the field would be wrong: Like lazy loaded properties.

But that is only a small step from treating the property as a first class object. Our getters and setters would then be overrides on that object. No getter and setter means we use the default implementation, which is the proposed shorthand definition.

Irregardless of the need for properties in winforms, classes still should not fully expose themselves. Properties allow for classes to provide information, but keep its inner workings secretive.

Writing wrapper code for a “just in case” scenario is not an option. I just do it. Bolt-on’s may be added later in the project, and the time for adding the bolt-on is usualy far less the time available for writing the initial framework code. Time lines change, and you can’t always just KISS until you’re biting the bullet on time and adding that functionality in the future.

I don’t want to be a dead horse (but I will):

“According to Microsoft’s coding guidelines, you shouldn’t prefix member variables with _ or m_ or any of that.”

This is not true. No Microsoft guidelines recommend this. The Framework Design Guidelines* only talk about public API (there are no naming guidelines for member fields - as we have guidelines that state these shouldn’t be public).

  • The internal ‘Microsoft’ guidelines were published in the book. However, these are neither official, nor used by most of the teams in Microsoft.

LOL…I meant to actually say ‘I don’t want to beat a dead horse’.

Here’s another example of the friction between property vs. public variable. This time the examples are Java and Ruby.

http://blog.grayproductions.net/articles/2006/03/10/java-a-bit-on-the-wordy-side

Have you ever had to locate where and when a Property is being set in an appliccation when the property name is something very common to your application? A search on the word gets you 100 times the amount of hits. The logical thing to do would be to put a break point on the property. However, when your property is a public variable, you won’t be able to do that, at least not in VB. This is my strongest argument against public variables.

The difference between a field and a property is essentially that a field is a place to store some data, where a property is a means to access some data. This may sound a little puristic, but I think separating the concepts of storage and access is important.

To make my point clearer:

class Sphere{
private float _radius;

public float Radius{
get{
return _radius;
}
set{
if( value = 0.0 ){ // sanity check for value
_radius = value;
}
else{
throw new ArgumentException();
}
}
} // property Radius

public float SurfaceArea{
get{
return 4*Math.Pow(Radius,2)*Math.PI;
}
} // property SurfaceArea

public float Volume{
get{
return 4*Math.Pow(Radius,3)*Math.PI/3.0;
}
} // property Volume

public float Diameter{
get{
return 2*Radius;
}
} // property Diameter

} // class Sphere

Also note that for the calculated properties, I do not access _radius directly, but use the public property Radius. In this case, it is highly improbable that the implementation of Radius may change, but you may at some point opt to store the diameter instead of the radius and calculate Radius instead.
In short, properties are an interface to data, while fields are storage locations. Declare your interface and use it: access the storage locations only through their interface.

Heh, just found this site… I was wondering what ppl thought about predominantly simple properties without any logic going on and I have become pretty much standardized in any public variable becoming a property. Plus, databinding is a given. But other than that…

one, it’s consistent. two, control when/if you need it. three, maintainability/expandability.

oh, and if it gets too long for ya and you don’t like scrolling it, just #region it. Too easy. And then you are done, and can start working on the more interesting stuff.

BTW, I use caps for props. ha, sorry, I just like it more. Looks clean. I’m Keeping It Simple Stupid, imho. :slight_smile:

check out orcas for automatic properties

http://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers.aspx