I am designing a class where some methods won't cause any harm if they are exposed as public. But they can be private as well, since they will be used only from the same class in my project.
Making them public has the following advantages:
Making them private has the following advantages:
Which are the general guidelines in this case?
In general, If the Method fits in the overall "Persona" of the class, make it public. More technically, try not to break the abstraction. I would have given an example, but I do not know the context of your work and so examples might be irrelevant. If you do not need it, there is no need to make a Method public.
Private methods are useful for breaking tasks up into smaller parts, or for preventing duplication of code which is needed often by other methods in a class, but should not be called outside of that class.
public - can be access by anyone anywhere. private - can only be accessed from with in the class it is a part of. protected - can only be accessed from with in the class or any object that inherits off of the class. Nothing is like null but in VB.
So what's the difference between a public and private function? A private function can only be used inside of it's parent function or module. A public function can be used inside or outside of it. Public functions can call private functions inside them, however, since they typically share the same scope.
Always make everything as private as possible.
For unit testing, I sometimes make a member internal, then use the InternalsVisibleTo
attribute in the AssemblyInfo.cs to permit the unit test assembly access to the internal members.
Oh, please please read Ch. 06 Of Code Complete 2 by Steve McConnell, if you have access to it. That will answer your question perfectly.
In general, If the Method fits in the overall "Persona" of the class, make it public. More technically, try not to break the abstraction. I would have given an example, but I do not know the context of your work and so examples might be irrelevant.
If you do not need it, there is no need to make a Method public.
For testing, +1 to John sanders.
But I really can not explain you here as Steve has explained in CC2.
I hope its OK to post Book references on Satckoverflow? (Please comment.)
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