The author provided a simple example which, due to its simplicity might make it more difficult for one to understand the importance of private methods.
Private methods are a way in which you can encapsulate and break down the behavior of a given object without exposing them to the outside.
Let us say that we have an object of type Person
:
public class Person
{
public string Name {get; set;}
public int Age {get; set;}
}
In the above, there is nothing stopping me from creating a person with a negative age:
Person p = new Persion() {Name = "Bob", Age = -1}
I could have a method to ensure that the age is within a set of established ranges.
public class Person
{
private int age;
public string Name {get; set;}
public int Age {get {return this.age}; set {this.ValidateAge(value);}
public void ValidateAge(int age) { if(age > 0) this.age = age; }
}
The problem now is that I have a ValidateAge
method which is exposed to who ever consumes the Person
class. This exposes an internal mechanism of the class and also provides a means to someone to change the internal data of the class without going through the appropriate property, thus breaking encapsulation.
Making the method private will hide it from outside callers, thus giving you better control over how and when are properties changed.