Showing posts with label Get. Show all posts
Showing posts with label Get. Show all posts

Wednesday, October 27, 2010

Why hide object state?

By restricting access to an objects internal state via getter behaviors, we can ensure that all values are valid before assigning them to internal state.

For instance, the Player class has a state called Name. If an external object has direct access to this state, there is the possibility that an incorrect or invalid value may be assigned to it, however, if that state can only be modified via a setter behavior, the behavior implementation (code) can check the value for its validity before assigning the value to the Name state. Eg. Is the name the correct length, type, etc.

Accessors: Get

Classes may contain accessor behaviors for some or all of their states. This enables other objects to read the value of a state. An accessor behavior is nearly always implemented as a function, as a function returns a value to the calling procedure.

For example, the Player class now contains a number of accessor behaviors. Following convention, the names of these behaviors begin with the word Get.

In a class diagram, the format for a behavior that returns a value(function) looks like this:
Visibility FunctionName(ParametersIfAny):ReturnDataType

...as can be seen in the Player class example:
+GetName():String

The implementation (code) for an accessor, reads and returns the value of the state being accessed. In other words, the GetName() function will return a String (containing the value of the Name state) to the calling procedure.

An accessor behavior has visibility of Public.