This question already has an answer here:
In object oriented programming, I used to have this question and I still do :
What would be the benefit of declaring a class member as private if we will create for it a public getter and a public setter?
I don't see any difference at the security level between the case above and the case of declaring the class member as public.
Thanks!
Declaring variables as
private
is called asEncapsulation in Java
.Here are few advantages of using Encapsulation while writing code in Java or any Object oriented programming language:
one more advantage is
If your class has no invariants to maintain then writing public getters and setters for a private data member is pointless; you should just use a public data member.
On the other hand, if you do have invariants to maintain then using a setter can allow you to restrict the values that can be assigned to the data member.
Note that just because you have a data member doesn't mean you have to write any getters or setters for it.
Pet peeve: "but what if the internals change?" It doesn't matter. You had a
getName
function that returned astd::string const&
. Getters reduce encapsulation because they constrain your choices when changing the implementation later on.Your question is indeed the difference between Fields and Properties. Fileds are usually private and properties do expose them. Bellow is a quote of a brilliant answer on SO:
What is the difference between a Field and a Property in C#?
In C# automatic properties will create a filed for you without having to manually declare it:
One of the most important concepts of Object Oriented Programming is encapsulation. You encapsulate data and the methods that act on that data together. Ideally, data should be accessed only via its related methods. And the state of data should be "queried" by other objects via these methods. Making a variable public will result in that variable being directly available to all other objects breaking encapsulation.
As with any encapsulation: it hides implementation details. This allows you to control access and provide a stable interface even when the internals change.
Setter controlling access
Getter useful during API evolution
If you have a data transfer object, with limited scope and by design it should have no logic associated with it, I don't see a value in getters and setters.
However, if you have a component which may or may not have some logic associated with it or it could be widely used, then it makes sense to hide the details of how the data is stored. Initially it might appear that all the getters and setters are trivial and just fill up you class, but over time you might add validation to the setters and even change the getters. e.g. you might drop a field (and return a constant in future), store the data in a delegated object or compute the value from other fields.