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();
}
Generally you should expose as little as possible and make everything private that is possible. If you make a mistake and hide something you should be exposing, no problem, just make it public.
Yes it is very bad practice - you're letting your tools make design decisions for you. I think the main problem here is that you're trying to treat each individual method as a unit. This is generally the cause of all unit test woes.
If a private method must call a public method, then the content of the public method should be taken and placed in a private method, which both methods can then call.
In Clean Code, Robert C. Martin advises coders to always put member variables at the top of the class (constants first, then private members) and methods should be ordered in such a way so that they read like a story that doesn't cause the reader to need to jump around the code too much.
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
Or, to put it in a single word: encapsulation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With