What are the practical difference between declaring a function private vs public?
class, methods, oop, vb.net
Solution
Encapsulation means that you should think of each class as a machine that provides a service. For example, a chair allows you to sit on it, or a lawnmower allows you to cut your lawn.
The private methods pertain to the machine's internal workings. In contrast, the public methods relate to how you (other classes) interact with the machine.
Example one: Chair...
When sitting on a chair, you don't need to know volume of stuffing or the number of staples, you basically need to know whether or not it's occupied and if it's stable.
- Public methods: IsStable, IsOccupied, Sit
- Private methods: CalculateStuffingVolume, CountNumberOfStaples
Example two: Lawnmower...
For the lawnmower, you need to know if it has enough fuel (or is plugged in), if the blades are sharp, and be able to turn it on.
- Public methods: GetFuelLevel, IsBladesSharp, TurnOn, TurnOff
- Private methods: Combust, etc, Too many to imagine.
Conclusion:
So when you're developing all you will see is...
Example one: Chair.Sit, Chair.IsStable and Chair.IsOccupied
or
Example two: Lawnmower.GetFuelLevel, Lawnmower.IsBladesSharp, Lawnmower.TurnOn, LawnMower.TurnOff
As a developer, you will not have to think about number of threads in the uphosltry, the colour of the fuel cap, the number of RPM of the blades or whether the chair is glued or stapled together. This distinction makes it much easier to put your application together without being swamped in detail. Additionally, it allows programmers to expose only necessary information which adds a level of security. As John mentioned, this prevents the Person class from calling Lawnmower.Combust(fuel) when they're not supposed to.
Problem
So as I've been reading/learning about classes and the methods within them I've found very little about the practical differences between declaring a method as public versus private. I know that the difference is a private class can only be accessed within the class, while a public method can be accessed from code outside the class (other classes, functions). But what I really want to know is: - Why would you want/not want to declare it one way or another when deploying an application? - Are there best practices that can guide whether to declare a method public vs private? Also, I don't know if it matters, but I am learning primarily VB.Net and C# in a web application environment, so specifics to that would help.