Hide data within its class

From CSSEMediaWiki
Jump to: navigation, search
All data should be hidden within its class. --Riel's heuristic 2.1, Arthur Riel 1996

All data should be hidden within its class. By data we mean the fields of a class that store data about the class. These fields should always be private, and only accessible to the methods of the class that contains them. This is called "information hiding." By ensuring that all data is private we simplify the maintenance of the program, because the implementation of a class can be updated or modified without changing the public interface of a class. This means that only the implementors of the modified class would have to change their code. If we were to make public fields in a class, and we later wish to change the implementation of a public field, we have to find and change the code of any classes that use the modified class.

For example consider a Transaction class with a public field that stores an array of prices of individual items purchased in the Transaction. If other classes want to determine the average price of an item in a Transaction, they would access the array to calculate the average:

2.1 example1.png

This may be all fine and dandy, until one day it is decided that the more information about individual Items needs to be stored, including the price of each one. We now need to change the implementation of Transaction to store an ArrayList of Items. This is a problem for maintenance of the program because now we also need to change the code of all the classes that access a Transaction's prices and expect it to be an array. A much better solution is to keep the data private within the class, and use a getter method to access the average price. This means that the implementation of how prices are stored in the Transaction class is hidden from other classes, and if the implementation needs to be changed, the public interface can remain the same. Here is the better solution:

2.1 example2.png

Now the getAverageItemPrice() will iterate through the ArrayList and calculate the average price of the Transaction Items. If the implementation of items needs to change again, only the getter method code will need to be updated, and the public interface will remain the same.


This heuristic assumes that Encapsulation boundary is the class.

See also

Personal tools