简体   繁体   中英

Method Calling Public/Private Members or Methods Best Practice - C#.NET

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();
}

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 .

在某些情况下,您的公共属性可能包含您需要的一些逻辑,在这种情况下,如果您确定要使用私有成员变量,并且不将该功能公开给该公共属性,那么您将始终使用该属性而不是局部变量。外面的世界,使那个特定的方法私有化。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM