Objects should hide data and expose methods
The state of your object is stored in member variables. These member variables are pieces of data. Data should not be directly accessible. You should only provide access to data via exposed methods and properties.
Why should you hide your data and expose your methods?
Hiding data and exposing methods is known in the OOP world as encapsulation. Encapsulation hides the inner workings of a class from the outside world. This makes it easy to be able to change value types without breaking existing implementations that rely on the class. Data can be made read/writable, writable, or read-only providing more flexibility to you regarding data access and usage. You can also validate input and prevent data from receiving invalid values. Encapsulating also makes testing your classes much easier, and you can make your classes more reusable and extendable.
Let’s look at an example.
An example of encapsulation
The following code example...