text: Sep 23, 2008 02:26 PM|diadem_2k|LINK
  One of my collegues argues with me NOT to write the properties just declare instance variables as public...but in my last 4+ years of .net programming I always expose properties and do programming and i thought that is the good programming practice....what is your opinion???
  Sep 23, 2008 03:07 PM|SGWellens|LINK
  If you need to make a public variable a property, by all means do so.
  If you don't need to make a public variable a property:
  To me, having uncluttered code is more beneficial. In the unlikely event you are changing the internal storage type, you are probably making other significant changes...you may have to change the property type anyway. (I've heard this argment several times but I've never seen it actually used).
  Sep 23, 2008 03:18 PM|JeffreyABecker|LINK
  AFAIK the reccomendation in .Net has always been to wrap fields in properties. The performance hit from a property is virtually non-existant. It allows you to easily put controls around who can set values. Many ORM systems and reflection-based frameworkds
  do not work well with Fields. The only real argument against it I can see is that its more code.
  Sep 23, 2008 03:49 PM|diadem_2k|LINK
  I am going to use reflections to read the property names and assign the database values to it...
  even i heard on msdn that writing properties is a good programming practice thats why i am following it....but the argument it is happening is more lines of code but for me that is not more lines of code...since we have short -cut which will create the property and only we need to play with set accessors...
  here...i am creating a business object ....thats why i am concerned that i should expose properties only....if this has been on a .aspx file, then i would have played with instance variables by making them public but when i am creating a business object which will be used by other people, then i thought exposing properties only would make some sense which holds with OOPs concenpt of data hiding or data excapsulation...
  thanks for giving some ideas....
  Sep 23, 2008 04:07 PM|rjcox|LINK
  Properties have three advantages over fields:
  Don't underestimate #3 when having problems with a non-trivial object graph.
  As noted above, JIT inlining will mean simple properties have no real overhead, and then can easily have logic added without changing the class interface (changing a field to a property, or visa versa, does change with the interface). With automatic properties
  it is now as easy to create a property as a field, so I really see no circumstances to use a public, non-static, field unless having to deal with a legacy fixed interface (including assumptions in reflection code).
  Sep 23, 2008 04:36 PM|Svante|LINK
  Unless you have a very specific reason, the answer is very simple. Don't expose public fields. Use properties and methods as appropriate. Period.
  There are lots of reasons why you should not expose public fields. Many, but not by far all, are listed in the previous answers.
  Ask your collegue for a single reason why you should. "Less to type" is not a valid answer.
  Sep 23, 2008 08:57 PM|Ricardojb|LINK
  In addition to everything already said, properties are the only way your object can be used in .net controls such a gridview for example.
  the .net framework uses reflection to find properties, you can't bind a column to a field.
  Also, if you are using .net 3.5 there is no difference between using properties and field in amount of coding, that if the get and set accessors simply set/get the value from a field, obviously, if you need more complex logic you can't use fields.
  Finally, I disagree with those who said the code is cleaner with fields, with a property somehow you encapsulate the value.
  Today a property can simply expose the value of a field, tomorrow you might need a more complex logic for the same value, you would only need to change the get and set accessors of the property while if you used a field you will have to do a less clean work.
  Sep 24, 2008 02:39 AM|SGWellens|LINK
  If you use properties when you don't need them, you pay a price. And not just typing, I used the editor's refactor menu to create the 2nd class below:
  // I prefer this...simple...clean public class RedMachine { public bool Valve1_Open; public bool Valve2_Open; public bool Valve3_Open; } // I avoid this when I can public class BlueMachine { private bool Valve1_Open; public bool Valve1_Open1 { get { return Valve1_Open; } set { Valve1_Open = value; } } private bool Valve2_Open; public bool Valve2_Open1 { get { return Valve2_Open; } set { Valve2_Open = value; } } private bool Valve3_Open; public bool Valve3_Open1 { get { return Valve3_Open; } set { Valve3_Open = value; } } }
  Sep 24, 2008 09:38 AM|Svante|LINK
  MacoleleChanging a instance variable to property is very easy.
  Sure.
  But what are you going to do about calling assemblies? Those that you have already deployed to one server or a million clients? Those that you did not even write yourself?
  I do not consider it good practice to require recompilation and redeployment of all dependent assemblies, just because you need to change an exposed public field to a property. When the cost to avoid this problem is zero, zilch, nil.
  It would be kind of interesting if the .NET framework was built using practices that required recompilation and recompilation of every single piece of .NET software on the planet, just because a software engineer at Microsoft required a public field to be changed to a public property... Fortunately it is built using better practices than that.
  This is just one of the many reasons why you should never expose public fields of a class, unless you have a very specific reason.
  It's more likely to be ok if they are internal, protected or private (of course all reflection-based code will break if you change then). But this discussion is about public properties/fields.
  Sep 24, 2008 09:52 AM|rjcox|LINK
  SGWellensIf you use properties when you don't need them, you pay a price
  I think you need to take a look at C#3, that would now be:
  public class RedMachine { public bool Value1_Open { get; set; } public bool Value2_Open { get; set; } public bool Value3_Open { get; set; } }
  Which, with the "prop" snippet only took a few seconds to type (and probably less than the field version).
  And now I have the ability to change the implementation of the three properties without changing the interface of the class.
  Sep 24, 2008 02:58 PM|SGWellens|LINK
  I am not against using properties. They have great advantages. I am simply pointing out they don't always provide useful benefits.
  Slavishly following a paradigm without any thought behind what you really need is not good programming.
  If you have a simple two page site and both pages access a common class why not keep the class as simple as possible?
  rjcoxAnd now I have the ability to change the implementation of the three properties without changing the interface of the class.
  Having the ability to do something you don't need to do isn't a very compelling point [:)]
  When was the last time you needed to change the implementation of a property and didn't change the interface?
  PS: This reminds me of the great 'tab vs spaces' debates of the 1980's.
  Sep 24, 2008 03:04 PM|rjcox|LINK
  SGWellensHaving the ability to do something you don't need to do isn't a very compelling point
  But I don't know I don't need to do it, yet.
  SGWellensWhen was the last time you needed to change the implementation of a property and didn't change the interface?
  Yesterday... and am going to be doing it again shortly. As part of refactoring the implementation of a type I'm working on.
  Underlying all of this: properties (due to JIT inlining and C#3's automatic properties) add no overhead and are as quick to write (thanks to the "prop" snippet) but increase flexibility, so I see no disadvantage over fields.
  Sep 24, 2008 07:52 PM|JeffreyABecker|LINK
  At the risk of sounding like a computer science professor...
  The fundamental arguments against fields are encapsulation and abstraction. Sure I want to keep my simple website simple but at the same time I want it to be maintainable. The OO principle of Encapsulation is all about who controls what. In the case of
  properties it gives the owner class control over the getting and setting of values. The more important principal here is Abstraction. Good OO dictates that the two web pages which consume our example class shouldnt really care how a particular property is
  stored and retrieved. If you're using Fields, you're making the pages care about the internal implementation of that class wether you mean to or not. Is not having to type 10 extra characters really worth throwing out the principals of good OO design?
  Member
  251 Points
  Sep 25, 2008 06:28 AM|pvkirankumar|LINK
  One good example I can give is .... DataHiding...
  for example my class has variables (we will think about their access specifiers later)
  like FirstName, LastName, MiddleName
  and I dont want to expose it to the other classes or other members , what i need to do is only expose name
  so, I will difine a public property called Name and concatinate what ever i requier (but all the 3 ,firstName, middleName and LastName i will be using for my internal purpose)
  as simple as that ..... I use it in terms of dataHiding
  rest .... a public variable and a public property are one and the same (at least my feeling)
  Rgds
  Kiran
  Sep 25, 2008 12:45 PM|SGWellens|LINK
  I think the subject of the original post has drifted.
  The question isn't: Do properties have beneficial features? (They do).
  The question was closer to: Should all public variables always be turned into properties?
  I come from the school that says, don't implement features that are not needed or used.
  Sep 25, 2008 12:58 PM|Svante|LINK
  SGWellensdon't implement features that are not needed or used.
  I hate to be obstinate, but I come from the school that says: Prepare for the unexpected. There's absolutely no way I can know beforehand if the benefits of a property will ever be needed or not.
  The point being that the cost of never using public fields, and only use properties (for public fields) is zero-to-negligable in run-time and irrelevant at keyboard-typing-time.
  The benefit being that I now have to option to modify the underlying implementation without breaking dependent code - which includes all separately compiled assemblies and all reflection based code that uses my class (it's possible, but hardly likely, that the reflection based code will be amenable to changes from fields to properties of the type being reflected).
  So, my definitive answer to the question:
  SGWellensShould all public variables always be turned into properties?
  Is "yes", even for internal classes since reflection based code will break otherwise.
  For private nested classes I'd say that it does not really matter, because the scope is so small.
  Sep 25, 2008 01:28 PM|SGWellens|LINK
  Svantebut I come from the school that says: Prepare for the unexpected.
  Me too, when writing "real" applications, I test/report the return result from every single function call.
  I think we're actually pretty close in our thinking: Robustness and Maintainability are good things.
  SvanteThere's absolutely no way I can know beforehand if the benefits of a property will ever be needed or not.
  I do, and maybe I can get you to grudgingly, partially, agree [:)].
  In my example, I deliberately used a bool to indicate if a valve was open or closed. The application is one page. It shows the status of the valve and allows the user to open or close it. I know, positively, that this type of valve is never partially open or closed (it will never be turned into an int or float). Even so, changes are trivial because there is only one class/code file. Properties provide no benefit in this scenario.
  Svante
  For private nested classes I'd say that it does not really matter, because the scope is so small.
  Right, so we agree, properties are not always appropriate or beneficial [:P].
  Sep 25, 2008 01:38 PM|Svante|LINK
  SGWellensit will never be turned into an int or float
  Quite so. That's not the problem.
  The problem is that a dependent assembly will be broken if you change the public boolean
  field ValveOpen to a public boolean property ValveOpen, because it turns out you need to change the way you determine if the valve is open or not.
  It's not about changing the type of the field/property - it's about changing the way it's accessed by dependent assemblies. The access is source code compatible, i.e. the it looks the same in source, but when compiled the two versions of the type containing ValveOpen are not compatible any longer, and the referring assembly will also require recompilation and redeployment.
  SGWellensproperties are not always appropriate or beneficial
  Not always beneficial, agreed (but it's a pretty rare occurrence). Never harmful. So why not stay on the safe side?
  Sep 25, 2008 04:31 PM|rjcox|LINK
  SGWellens
  The question isn't: Do properties have beneficial features? (They do).
  The question was closer to: Should all public variables always be turned into properties?
  And the question being answered is: Are there any circumstances under which a public field is better than a public property?
  To which the answer is: almost never (the MinValue/MaxValue/Zero usage for value types being the only significant case of using a field, and these are public
  static fields).
  Sep 25, 2008 04:58 PM|JeffreyABecker|LINK
  SGWellens
  I think the subject of the original post has drifted.
  But we're all having such fun with the flame war!".
  The question was closer to: Should all public variables always be turned into properties?
  Sep 25, 2008 05:06 PM|Svante|LINK
  JeffreyABeckerflame war
  "Don't mention the war!" (See for an explanation...)
  Seriously - we're not having a war are we? I hope nobody feels stepped upon, I'm participating because it's a fairly important issue (well.. as C# forum issues goes - not in a global view of things...) but I'm not trying to flame anyone, and I don't feel
  flamed either.
  Sep 25, 2008 05:23 PM|JeffreyABecker|LINK
  Nah, we're just having a long-winded disagreement. I most certianly hope that I've not hurt anyone's feelings and that Steve doesnt feel gang-up-on here.
  Sep 25, 2008 05:57 PM|SGWellens|LINK
  JeffreyABeckerI most certianly hope that I've not hurt anyone's feelings and that Steve doesnt feel gang-up-on here.
  I do feel ganged-up on but I don't mind. At one time, the majority of people on this planet thought the world was flat...and the last time I checked, it was roughly sphere shaped [:)]
  And I'm glad there is a minimum of posts repeating the same point over and.
  I hope we don't get into trouble with the SPCA for beating this dead horse.
  Sep 25, 2008 06:56 PM|JeffreyABecker|LINK
  SGWell.
  See I dont think that's the type of change we're talking about. Lets consider a concrete example I recently ran into...
  We have a part of our application which implements a decision tree. Long, long ago we had a single class RuleNode which had every property of every possible type of node as well as DescisionID, NodeID, NodeType and Children. Thankfully this code was refactored into abstract RuleNode class that had DescisionID, NodeID and NodeType and implemented IList<RuleNode> and about 12 derived classes with the various properties appropriate to them. However the database remained a single gigantic table with lots of nulls and the loading code was basically a big blob of "if(n.Type == RuleNodeType.Foo) load these properties". More recently we refactored the database into several tables something like:
  RuleNodeType: TypeID int, TypeName varchar(255)
  RuleNodeAttribute: AttributeID int, AttributeName varchar(255), ConversionType varchar(255)
  RuleNodeTypeAttribute TypeID int, AttributeID int
  RuleNodeValue DescisionID int, RuleNodeID int, AttributeID int, Value sql_variant
  Then we added a member and constructor to our abstract base class as such:
  protected IDictionary<RuleNodeAttributes,object> AttributeValues {get;set;}
  protected RuleNode(IDictionary<RuleNodeAttributes,object> objectValues);
  so all the various Properties of our objects went from looking like:
  private int _PhaseOfMoon;
  public int PhaseOfMoon
  {
  get{ return _PhaseOfMoon;}
  set{ _PhaseOfMoon = value;}
  }
  to:
  public int PhaseOfMoon
  {
  get{ return (int)AttributeValues[RuleNodeAttributes.PhaseOfMoon];}
  set{ AttributeValues[RuleNodeAttributes.PhaseOfMoon] = value;}
  }
  This eliminated about 2.5k lines of loading / saving code and reduced server-load time by over 60%. If the Attributes in question had been fields, we would not have been able to do this. Properties abstract away the implementation of fields so you can do things like back a field with a dictionary or lazy load a particularly heavy sub-object.
  Sep 25, 2008 10:43 PM|SGWellens|LINK
  Jeffery,
  I get that. I'm not arguing that point. If your class is exposed in a DLL and there are several applications that use it that can't be rebuilt if there is an interface change, then, by golly, properties are beneficial.
  But, if some one decides PhaseOfMoon should be a fraction (1/4, 1/2, 1.0 = full), then you've got to change the internal representation AND the property. So instead of reducing maintenance, in some cases using properties can increase maintenance.
  Sep 25, 2008 11:27 PM|JeffreyABecker|LINK
  See I'd say that's outside the scope of the argument. I've rarely changed a data-type on an attribute of a class without changing the representation I'm using. If I'm changing PhaseOfMoon to be a float or enum or whatever, changing 3 lines in the class it belongs to is the least of my worries. Now I have to go do in-depth analysis and probably modification of all code which accesses PhaseOfMoon to make sure that it still uses the property correctly.
  Also, as Savnte pointed out earlier,
  Automatic Properties in C# 3.0 make this argument pretty much a moot point.
  Sep 26, 2008 03:17 AM|SGWellens|LINK
  JeffreyABeckerSee I'd say that's outside the scope of the argument.
  I thought that was the discussion [:)]
  I agree that Automatic Properties do make creating properties easier...but then that's not quite the point.
  Gee, I think everyone else has gotten bored with this topic and left...
  So here's a barely-on-topic story. I was working on a C++ project with five other developers and one of them insisted on "wrapping" some fields...at that time he added get and set functions. He said he was protecting his variables. I bet him a dollar I could change his variables even with his protection. He took the bet. I checked his file out of source control, made the variable public instead of private, checked it back in and then proceeded to set it to an illegal value....it wasn't hard [:|]. He didn't want to pay but the other developers made him.
  Sep 26, 2008 04:26 PM|JeffreyABecker|LINK
  Wow, I wouldnt have even gone so far as to make it public. I mean why not just do some pointer arithematic and set the value? Protection is a red-herring. The issue I have with fields is they're a bad abstraction. The principles of OO as I was taught
  them say that consumers of my classes, even if that consumer is inside the assembly shouldnt care how I go about making them work.
  28 replies
  Last post Sep 26, 2008 04:26 PM by JeffreyABecker