Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

oop

ooad

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();
}
like image 513
traderde Avatar asked May 26 '10 10:05

traderde


People also ask

Should my method be public or private?

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.

Is it good practice to make all methods 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.

Can private method call public method?

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.

Should private methods be on top or bottom?

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.


1 Answers

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.

like image 194
Fredrik Mörk Avatar answered Nov 11 '22 14:11

Fredrik Mörk