tags:

views:

138

answers:

2

What is the best practice for calling members/fields from a private method and public method? Should the private method always call private fields or should they call the public members?

private string _name;
public string Name
{ 
   get {return _name; }
   set { _name = value; }
}

public void DoSomething()
{
   _doSomething();
}


private void _doSomething()
{
   _name.ToLower();
}
+6  A: 

I prefer to have all code go through the public interface, simply to reduce the number of places in the code that accesses the actual backing field. Two reasons are

  • Simplifies debugging; if you have an issue where a value is changed, or returns an unexpected value, you can set a breakpoint inside the property getter or setter and easily trap any access to the value.
  • Reduces impact of changes, you can make changes to the field and it will affect very few places in the code directly.

Or, to put it in a single word: encapsulation.

Fredrik Mörk
+ lots for "encapsulation". As Steve McConnell put it in Code Complete, without encapsulation, you don't have abstraction, either.
Cylon Cat
+1  A: 

In some cases your public property might contain some logic which you need and in that case you will always use the property instead of the local variable, if you are sure that you want to use the private member variable, and not expose that functionality to the outside world, make that particular method private.

PieterG