views:

251

answers:

7

E.g. which way is better

class Foo {
private string _Bar ; 
  Foo ( string bar)
  {
    _Bar = bar ; 
  }
 public string Bar 
 { 
   get { return _Bar ; //more logic here
   } 
   set { _Bar = value ;   //more logic could be added
  }
 }
}

OR

class Foo {
private string _Bar ; 
  Foo ( string bar)
  {
    this.Bar = bar ; 
  }
 public string Bar { 
  get { return _Bar ; //more logic could be added } 
  set { _Bar = value ; //more logic could be added }}
}

Edit: I know that the latter allows to put some more logic in it , yet is it justifiable to use it because of it ...

+1  A: 

It depends.

I prefer using the properties, when there are no side effects. There are times, however, when setting a property has other side effects, such as event notification, potentially unnecessary (at this point) validation, etc. In those cases, setting the backing field directly is a better option.

Reed Copsey
+5  A: 

Whichever way makes sense for the class; there is no "best practice".

Sometimes you might want to ensure that you only perform the same operations the property could; in which case it makes sense to use the property.

Sometimes you want to do things that can only be done in the constructor which violate the things you can do via the property post-construction, in which case it makes sense to use the field.

Greg Beech
+1  A: 

It depends, if you need the logic in the public property to be executed, use that method. If you are just doing a straight assignment, then assigning to the private member is fine.

Steve Dignan
A: 

Please read this excellent blog post by Eric Lippert: Automatic vs Explicit Properties :

Here's a question I got from a C# user last year, a question I get fairly frequently:

User: With “regular” explicit properties, I tend to use the private backing field directly from within the class. Of course, with an automatic property, you can’t do this. My concern is that in the future, if I decide I need an explicit property for whatever reason, I’m left with the choice of changing the class implementation to use the new private field, or continue going through the property. I’m not sure what the right thing to do in this case is.

You say “for whatever reason”, and that's key. The answer to your question will depend entirely upon what the reason was that motivated the change.

If the reason that motivated the change from automatically implemented property to explicitly implemented property was to change the semantics of the property then you should evaluate whether the desired semantics when accessing the property from within the class are identical to or different from the desired semantics when accessing the property from outside the class. [emphasis mine]

Andrew Hare
+1  A: 

I often use the properties, as it allows me to only write my validation in one place (the property setter). It helps avoid duplicate code.

public class Foo
{
   private string _Bar = String.Empty;

   public string Bar
   {
      get { return _Bar; }
      set 
      {
          if (value == null)
             throw new ArgumentNullException("Bar");
          _Bar = value;
      }
   }

   public Foo(string bar)
   {
      Bar = bar;
   }
}
C. Ross
A: 

Your example is a bit too simple, but your comment "//more logic could be added" alludes to the possibility that the set property could be more complex than a simple assignment to a private variable.

Don't repeat the same logic in the constructor if you have already coded the same logic in the property set. This would be unnecessary duplicate code, and could be error prone when the logic needs to change and is a pain in the neck for a developer in the future who has to maintain your code.

If your set property has some side-effect that would be unwanted/unneeded in the constructor like event notification then you should refactor the common code to its own method. The constructor and set property can both call this method.

You're going to get a lot of "it depends" answers because, well, it depends. Some of the reason for that is going to be personal preference (often determined by past experience where something was hard to maintain or buggy). Some of the reason it that every situation is different, and while there is certainly a lot of common patterns and tasks we implement with code there always needs to be the possibility of not following the norm to be creative or innovative in your coding solutions to your problem. Remember we don't program code, we program solutions using code as tool.

Adam Porad
A: 

I'll put some flesh on my "it depends" answer: you're trying to find a balance between making sure that the internal state remains consistent, duplication of code, and performance.

I agree w/Adam P, because your current example is very simple it really doesn't matter.

Consider an example where a readonly variable Qux is dependent on Bar and another member Baz. Qux is fairly costly to calculate, so you wouldn't want to do it on the fly -- this suggests a private field to store the state, and change it IFF Bar and Baz change.

So in your constructor you could set Bar and Baz publicly, knowing that Qux will be resolved twice, or defer the resolution of Qux until the end of the constructor (and save one Qux resolution call).

In fairly trivial code that is not likely to change (e.g. public properties backing simple private fields), pick one style, stick with it, and concentrate on solving your programs real problems.

micahtan