I wasn't sure how to formulate the title, but there's something that's made little sense to me in OOP
I understand the idea of encapsulation, which is to create a layer of protection, and abstraction, so that there's no direct access to a given variable.
However, there are cases where encapsulation doesn't make any sense to me, allow me to demonstrate using a simple C# class:
public class Person
{
public int Age { get; private set; } // makes sense, the setter is isolated
public string Name { get; private set; } // same story
public string ZipCode { get; set; } // doesn't make sense
public string Country { get; set; } // doesn't make sense either
public string City // also makes sense
{
get { /*some logic that gets the city based on zip code and country */ }
private set;
}
}
My issue here is that, according to good OOP practices, variables without any special rules, must also have separate accessors and mutators, but why should they if all you do anyway is set and get data to and from them?
In the case of Age
and Name
it makes sense to encapsulate it, because the setter is private, you can't mutate it outside the scope of the class, likewise with the City
field, that has a special getter, that gets the data based on special rules.
What difference does it make if I wrap ZipCode
and Country
in a property or not? I can fully access and mutate the variables in either case.
Could someone clarify this?