Properties vs. Public Variables

#1

I occasionally see code with properties like this:

private int name;

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


This is a companion discussion topic for the original blog entry at: http://www.codinghorror.com/blog/2006/08/properties-vs-public-variables.html
#2

“All style guidelines aside, you know that ain’t right.”

but to add “m_” is right…

#3

I’m no fan of “m_”, but SCREAMING_CAPS is beyond the pale.

#4

So how do you name your constants then?
I use the SCREAMING_CAPS. But then again I’m an old mainframe hack, so it just feels right.

#5

I agree that the trivial property implementation of exposing a data member is a lot of code for no gain. But, I’ve run into several people who get religious that public members are verboten!

Nonsense. The only rational reasons I can think of to have simple getters/setters around a private member variable are:

  1. to provide read-only access to a member var that cannot be declared const for some reason
  2. if you’re writing a component that is meant for use by some 3rd parties and there exists any chance that the component will have to be replaced without requiring a rebuild by those users (changing a public member variable to a property breaks the interface, so a rebuild is needed).
#6

If only you could refactor a field into a property later…

Say you have 2 assemblies: MyCompany.Domain and MyCompany.UI. Domain defines a User class with a Name field. UI points to a statically compiled copy of Domain and uses User in a few places.

Time goes by and a legitimate need to refactor Name into a property arises, so Domain gets recompiled and dropped into UI and…

System.MissingFieldException: Field not found: ‘MyCompany.Domain.User.Id’.

Despite the syntax similarities between accessing fields and properties, they are very different things. So if you’re ever going to turn Name into a property and if anyone’s ever going to point at your library without being able to recompile from source, you should definately use a property from the get go. It is, unfortunately, the simplest thing that will possibly work.

#7

I think the scope matters here. I tend to wrap public fields in properties, for two reasons - one is that you can’t change it later without breaking binary compatibility. Two is that you can’t bind to fields. For strictly internal fields, however, I agree that just using fields is OK.

I really don’t like m_, as it can be a gateway drug to hungarian, but I’ve learned to accept _.

I’m with you on the screaming-cap const thing. Shudder.

#8

And while we’re on the subject…

Reflection code against fields looks very different from reflection code against properties (FieldInfo vs. PropertyInfo for starters). So even if you can recompile against the new binary, if you use reflection on that field you’re hosed.

#9

Like Kevin says, databinding doesn’t work with Fields. With code snippets and tools like CodeRush or ReSharper these things are so painfully simple there’s no reason not to.

Also consider this. In using an OR/M such as NHibernate and you need to populate your objects from a database, assuming you follow a Persistent-Ignorant object approach (as opposed to, say, ActiveRecord) you won’t be able to set those readonly fields unless you use a readonly property. A public readonly member can not be set via reflection, so this is a big concern.

I think it’s a worth-while practice to get into and it doesn’t cost much :wink:

#10

As long as it is not hungarian or some variation such as Leszynski/Reddick and is consistant I am usally happy.

In Java the language recommended namining convention s uses the all caps and underscores for final variables aka constants. The reason they give is that it aids in debugging, but also has its beginning in the C days with #define.

Personally I see it kind of falling back into the hungarian problem, what if you do go and change it from a constant value to something that can change? However on the other side and the reason I do still use the all caps and underscore is that constants are special beasts and yes using a different naming convention does make them stick out, and in some instances you do get a fair amount of public constant variables and having them using a different convention makes sure you don’t have conflicts.

#11

…and while we’re on the subject of naming practices…

I agree that a variable called strName is kind of stupid and pointless.

But what about ASP.NET controls on a page (or winforms) ? I whole-heartedly agree with naming textboxes like txtName or lblMessage, dgCustomers, etc. This is a good way to distinguish local private members from page controls.

The reason I bring it up is because on my current project all of the control names match up with database columns (shudder) and they use a large series of helper methods to make crud forms easy to bind to. (so txtFirstName becomes FirstName)

#12

One other thing - I do wish Microsoft would let us write:

public property int Name;

Which would let us expand a trivial property declaration into a real property get/set without breaking compatiblity. Maybe some day.

Hey, wait a sec…why in god’s name does your sample use “int” as the data type for a name? :wink:

#13

On issue with dotnet is that during databinding only properties are seen. Public member variables are not. So any object that you might bind to a a GridView or the like must be a property.

The other nice thing in dotnet 2.0 is the ability to set access control on the get or set. So sometimes I end up doing this:

public int Name
{
get { return _Name; }
internal set { _Name = value; }
}

You can’t do this with a variable.

#14

My given name is 75012, but my friends call me “Jeff”.

#15

However on the other side and the reason I do still use the all caps and underscore

Less code? That’s a worthwhile cause deserving of serious discussion.

But whether you call something “foo”, “Foo”, “_foo”, or “FOO”? Meh.

Naming conventions are highly controversial and religious. Developers should pick something they like, something that’s hopefully not too much at odds with the “local conventions”, and just go with it. A lot of discussion and hand-wringing over naming isn’t worthwhile.

That said, I think ALL CAPS IS REALLY HARD TO READ!

#16

I think the all caps makes sense. It’s a quick way to determine that the value is in fact a Const. It’s not a ‘variable’ that is being set or is changing elsewhere. To a developer who has to support my code, they simply see the all caps and can immediately determine that this is in fact a hard-coded value.

#17

I’m a huge fan of always wrapping my fields with properties…it just feels right.

To me the effort in wrapping is minimal (having a macro that creates either readonly or normal properties for the selected fields helps). When I see code that just has a mixture of public fields and properties IMHO it smacks of laziness.

But I agree with the earlier comment about context. I mostlt develop domain layer code…so my classes generally fall into three categories: services, entities and value objects. I like all my value objects to be immutable (which properties help with), my O/RM likes entities to have properties, and my service classes generally don’t need properties.

At our company we don’t use hungarian (except maybe in web apps) but we do use scope prefixes: m_, p_ and s_ (s_ is for static fields, and p_ is for parameters).

When I was first introduced to p_ for parameters i HATED it, but my project lead at the time said that the feeling would pass after two days…and it did. I use it all the time now and find it incredibly useful. It’s kindof hard to explain but I don’t know anyone who’s tried it for a couple days who doesn’t then go on to use it all the time.

#18

p_ is for parameters

Ick! Ack! Uck! (Run screaming).

I have no problem with local coding style variations, but something that makes my code looks dramatically different from virtually all the rest of the .NET code “out there”? No thanks.

Observing the conventions of the framework is my number one rule.

#19

Holy fark. The advice on fields vs. properties is totally wrong, wrong, wrong, wrong, wrong.

I suggest, no, insist, you read Effective C#: http://www.amazon.com/gp/product/0321245660/sr=8-1/qid=1155081911/ref=pd_bbs_1/002-4539717-3298461?ie=UTF8.

If you think it’s “difficult” to write all those getters and setters, here’s a free VS plugin to create them:

http://www.adersoftware.com/index.cfm?page=vsPropertyGenerator2

#20

Clearly there’s a lot of friction in the seemingly minor distinction between a property and a variable. A coworker and I were just discussing this. Here’s a idea he had:

Why not do away with variables in favor of properties?

That’s one Gordian Knot-esque way to reduce the friction. And why not? How are variables really adding value? Don’t properties do exactly the same thing, but with better granular control over visibility?

Also, I really like Kevin Dente’s idea:

public property int Name;

Paging Anders Hejlsberg…