Properties vs. Public Variables

Does anyone else avoid constants in favour of app.config Settings when appropriate? Similar to static readonly objects (promoted in Effective C#), using app settings can be changed without rebuilding (the values aren’t being inlined), and if you want to document those settings within the class structure you can wrap them in static properties (though if you don’t like the loose relationship with settings and classes you can just use the default settings wrapper, it just takes longer to write out):

/// summary/
public static object AppSettingValue
{
get { return Properties.Settings.Default.AppSettingValue } ;
}

I came to this page looking for THE final solution to this problem. I quickly went through the comments and I think Ian Griffiths is into something.

I cannot decide: a suffix, or maybe still a prefix. I think it must be short (dont like PropertyValue much). Maybe “value”, perhaps “internal”, “inner”, “hidden”, “field”, “store”, “holder”, “keeper”… “state”… “innerState”?

Not 100% satisfied with any, but I guess I will go with “value” or “state”. Perhaps someday an idiom will be stablished.

I have just found this paper by Robert Martin:

http://www.objectmentor.com/resources/articles/lsp.pdf

He uses an “its” prefix for private fields holding property values. The examples are in C++ so there are not actual properties, but read/write accesors.

I wanted to revisit this post because I think this prefix is very close to being the one. The only doubt that remains is that perhaps Ian is right and having a longer prefix/suffix is a good thing.

@Jeff Atwood :

I think the static const int TRIGGER_COUNT = 100; should read const int TRIGGER_COUNT = 100;

Start with the simplest thing that works-- a public variable. You can always refactor this later into a property

Yes, but then you’ve got a mix of public fields and properties, which has the following problems:

  • A little harder to debug since you have to look in a couple places potentially

  • A lot harder to regenerate your class if you’re using code generation

  • A little harder to explain your system when another developer starts working on the project

Yeah, I gotta say I usually go with screaming caps. I don’t like to use scope prefixes, but I usually do like to use constants. Over time I usually promote them to command line arguments or configuration settings and change the case at that time. I agree that it’s nice to glance at a function and see what’s being set at compile time.

Obligatory “Ruby does this right” post. Hardly needs to be said by this point- we can pretty much assume that if you’re being irritated by a feature of the .net languages a quick check of the Ruby docs will show a way in which the problem has been solved…

According to Microsoft’s coding guidelines, you shouldn’t prefix member variables with _ or m_ or any of that. So you have three choices if you follow that guideline:

  1. Don’t wrap with properties, just use public fields;
  2. Use camelCaps for the member variable and PascalCaps for the property (Microsoft’s recommendation); or
  3. Create two distinct names for every single field.

No developer is going to waste time on #3, and since VB.NET doesn’t allow #2, and since your experience has largely been with VB (I don’t mean that negatively, honestly), it explains why you advocate either #1 or the MS-disapproved member prefix.

I eschew the exploitation of case sensitivity most of the time, but it actually kind of makes for field-accessor properties. A maintenance coder does not even need to search for the property declaration to know that, yes, the property is really just a wrapper for some member variable. Unless it isn’t just a wrapper, in which case the naming is totally wrong. And obviously this isn’t a valid convention in VB or other case-insensitive languages.

I think it would be a great idea to be able to use a “property” syntax. Delphi actually has this syntax although it’s not quite the same thing:

SomeProp: Integer read FSomeProp write SetSomeProp;

Where “FSomeProp” is the field name according to Delphi’s naming conventions and SetMyProp is a method. The “write” doesn’t have to be a method, it could also be FSomeProp. The beauty of this is that you don’t actually have to make the stupid “getter” and “setter” methods - you can link both assignments directly to the member variable, which means only one extra line of code. And you don’t even need to write that code - just write the property and Delphi’s class completion will insert the member variable.

As an aside, Delphi (Pascal) is not case sensitive, hence the “F” prefix. I’m not for or against case sensitivity, I’ll use whichever conventions are accepted for the language I’m using at the time.

It’s not perfect but it is a lot less clunky than C#, and I think they really need a better property syntax. It would be especially nice not to have any extra code at all and declare a property/field hybrid like Kevin’s. C# already has this syntax for Events, so why the hell not Properties? Although I’m not sure if it makes sense to completely ditch fields in favour of properties because properties can be non-trivial overhead, and private member data is the most likely data to be used in long loops. People will argue that it’s trivial overhead but it’s also a trivial productivity boost - is it really worth the trade?

As for the distinction between local and member variables, it was a bit of a pain at first, but I’ve taken to using the “this” reference. It just makes sense, especially in constructors where you are literally initializing the member variables through parameters, and thus the parameters ought to have the same names as the member variables so - once again - anybody who reads the constructor can figure out what’s going on.

I think my reply was longer than the original post. Oh well, we are talking about verbosity here! :slight_smile:

Has anyone suggested the “property” keyword to the C# team? It is, as Haacked pointed out, merely syntactic sugar, so I don’t imagine it would be too hard for them to implement. And since it already sort of exists in Delphi, which was Hejlsberg’s brainchild, it stands to reason that he already knows what’s involved.

With all the craziness they’re adding to the new version like Linq, anonymous types and so on, this one ought to be a no-brainer.

"Why waste everyone’s time with a bunch of meaningless just-in-case wrapper code?"
think of an extreme case. you have a data transaction object that represents a person, and is used in 60,000 places in your enterprise application. The client has just requested that all first name attributes have to have the first letter capitalized, and the middle name abbreviated to one letter. Now if the dto had public accessors, you would have to change the format of these attributes in 60,000 places. But if you encapsulated the attributes you would only have to change one line of code in the dto person class.

I know consts are what we’re “supposed” to do, but I bl**dy hate them and the way they’re done here’s an example of piece of javascript code i was looking at tonight

dialogHtml = dialogHtml
  .replaceAll(WYM_BASE_PATH, this._options.basePath)
  .replaceAll(WYM_CSS_PATH, this._options.cssPath)
  .replaceAll(WYM_WYM_PATH, this._options.wymPath)
  .replaceAll(WYM_JQUERY_PATH, this._options.jQueryPath)
  .replaceAll(WYM_DIALOG_TITLE, this.encloseString(sType))
  .replaceAll(WYM_DIALOG_BODY, sBodyHtml)
  .replaceAll(WYM_INDEX, this._index);

What hell does that mean? To work out whats going on here, i’ve got to hunt down the CONSTs and the _options and then get back here to piece it all togehter, nightmare! There’s got to be a better solution than this, this is nasty. Using consts in Javascript is particullary bad as there is very limited support for intellisense in js IDE’s(that i know of) but a lot of people do it. Anyone got a better solution? As for properties, check out .net 3.5 auto-properties, ooh yeh!
public class Customer{
public int CustomerID { get; set; }
public string CompanyName { get; set; }
public Address BusinessAddress { get; set; }
public string Phone { get; set; }
}

In my previous job we used to use these naming conventions:

public class Employer
{
private static int ourEmployeesCount; // static - our
private string myName; // fields - my
private int myAge;

public string Name
{ get { return myName; } }

public int Age
{ get { return myAge; } }

public Employer(string theName, int theDateOfBirth) // params - the
{
    int anAge = DateTime.Today.Year - theDateOfBirth;   // local variable - a, an

    myName = theName;
    myAge = anAge;
    ourEmployeesCount++;
}

}

Just my 5 cents :slight_smile:

Property always a better choice instead of public variables.Property is safe while public variables are unsafe. And you can not debug with public variables but you can do that with property.

For more detail please see
http://interview-preparation-for-you.blogspot.com/2010/12/why-property-is-better-choice-instead.html

coding standard’s are always said to be enforced no matter whether you are writing bash script using parameters or java program using classes, yet people don’t follow them why ?? could be many reason but foremost reason is awareness, laziness and simply don’t care attitude. but until coder is consistent with existing code lines I would let them go with fancy coding practice.

Very late to the party on this but FYI this is what Microsoft have to say on the subject:

Note Don’t implement a property as a public variable just to avoid the overhead of a function call. Behind the scenes, Visual Basic will implement the public variables in your class modules as pairs of property procedures anyway, because this is required by the type library.

So if there is any restriction on the valid data beyond those of the basic data type or additional processing needs to be done whenever the value changes implement it as a property.

I am a simple man, I find this to be beautiful:
public string Name;

If I want limited access control - I’d use “proper” property/getter. Until then, I’d use the above syntax.

There is nothing amazing in declaring: public string Name { get; set; }
It basically means:
“I am a public variable with a unrestricted access, but i am declared as property, because one day someone may actually add a real Get body with code, if need finer access to me…So, just in case, I am declared in this way, so the interface won’t break. More over, you can data-bind me easier, with some half-baked lib. And also i am easier to use in a public assembly interface…”

Basically, the developer is forced to think about 10 external limitations, instead of having nice, tide code - easy to read and understand…

1 Like

From my time on reflection emission and the general IL playground i’ve noticed that if you want performance, a field or variable is the way to go, since a property in the background creates a hidden field , getter & setter. ofc you are not gonna experience a major boost in performance, but less IL loops to jump through.

1 Like