Set and Get methods can validate attempts to modify private
data and control how that data is presented to the caller, respectively. These are compelling software engineering benefits. If an instance variable were public
, any client of the class could see the data and modify it, including setting it to an invalid value. Also, public
data allows client-code programmers to write code that depends on the class’s data format. If the class’s owner changes that format, any client code dependent on it would “break” and would need to be adjusted to the new format, making it subject to break again.
You might think that even though a client of the class cannot directly access a private
instance variable, the client can nevertheless do whatever it wants with the variable through public
Set and Get methods. You’d think that you could peek at the private
data (and see exactly how it’s stored in the object) any time with the public
Get method and that you could modify the private
data at will through the public
Set method.
Actually, Set methods can be programmed to validate their arguments and reject any attempts to Set the data to bad values, such as
a negative body temperature
a day in March outside the range 1 through 31
a product code not in the company’s product catalog, etc.
A Get method can present the data in a different form, while the actual data representation remains hidden from the user. For example, a Grade
class might store a grade
instance variable as an int
between 0 and 100, but a GetGrade
method might return a letter grade as a string
, such as "A"
for grades between 90 and 100, "B"
for grades between 80 and 89, …—we’ll do this in Section 5.7 with a property. Tightly controlling the access to and presentation of private
data can greatly reduce errors, while increasing the robustness, security and usability of your programs.
Account
Object with private
DataYou can think of an Account
object as shown in Fig. 4.4. The private
instance variable name
is hidden inside the object (represented by the inner circle containing name
) and guarded by an outer layer of public
methods (represented by the outer circle containing GetName
and SetName
). Any client code that needs to interact with the Account
object can do so only by calling the public
methods of the protective outer layer.
Generally, instance variables should be private
and methods public
.
Change is the rule rather than the exception. You should anticipate that your code will be modified, and possibly often. Using public
Set and Get methods to control access to private
data makes programs clearer and easier to maintain.