Java Reference
In-Depth Information
Limitations of class methods
Because class methods are associated with a class rather than an instance, they have two impor-
tant limitations. The first limitation is that a class method may not access any instance fields de-
fined in the class. This is logical, because instance fields are associated with individual objects.
Instead, class methods are restricted to accessing class variables from their class. The second
limitation is like the first: a class method may not call an instance method from the class. A
class method may only invoke other class methods defined in its class.
You will find that we make very little use of class methods in the examples in this topic.
In this chapter, we have discussed what are often called the nonfunctional aspects of an appli-
cation. Here, the issue is not so much to get a program to perform a certain task, but to do this
with well-designed classes.
Good class design can make a huge difference when an application needs to be corrected, modi-
fied, or extended. It also allows us to reuse parts of the application in other contexts (for exam-
ple, for other projects) and thus creates benefits later.
There are two key concepts under which class design can be evaluated: coupling and cohesion.
Coupling refers to the interconnectedness of classes, cohesion to modularization into appropri-
ate units. Good design exhibits loose coupling and high cohesion.
One way to achieve a good structure is to follow a process of responsibility-driven design.
Whenever we add a function to the application, we try to identify which class should be respon-
sible for which part of the task.
When extending a program, we use regular refactoring to adapt the design to changing require-
ments and to ensure that classes and methods remain cohesive and loosely coupled.
Terms introduced in this chapter
code duplication, coupling, cohesion, encapsulation, responsibility-driven
design, implicit coupling, refactoring, class method
Concept summary
coupling The term coupling describes the interconnectedness of classes. We strive for loose
coupling in a system—that is, a system where each class is largely independent and commu-
nicates with other classes via a small, well-defined interface.
cohesion The term cohesion describes how well a unit of code maps to a logical task or en-
tity. In a highly cohesive system, each unit of code (method, class, or module) is responsible
for a well-defined task or entity. Good class design exhibits a high degree of cohesion.
Search WWH ::

Custom Search