Java Reference
In-Depth Information
The following
Employee
class is tightly coupled to
Address
because
Employee
makes
multiple accesses to the
Address
class, directly accessing the
street
,
city
, and
zip
fi elds of
Address
:
public class Employee {
private Address home;
public Employee(String street, String city, int zip) {
home = new Address();
home.street = street;
home.city = city;
home.zip = zip;
}
}
Making changes to
Address
has a direct effect on
Employee
. For example, if we need to
change the
city
fi eld in
Address
from a
String
to a
StringBuffer
, the
Employee
class no
longer compiles. The ripple effect of tight coupling can quickly get out of hand, and it can
become tedious and diffi cult to maintain the code.
You can avoid this situation by using loose coupling. With loose coupling, changing
code in one class can have a minimal effect on its dependent classes. In addition, loose
coupling increases the reusability of your classes because a class is more readily used and
extended when it is not dependent on other classes.
Loose Coupling and Tight Encapsulation
Implementing loose coupling actually works in close association with tight encapsulation.
One of the design techniques of loose coupling is to make the fi elds of a class
private
and only access them through
public
methods, which is exactly how we implement tight
encapsulation. By making the fi elds
private
and using tight encapsulation, we loosen the
coupling between classes because the fi elds of a class are not accessed directly, as we
demonstrate in the
Employee2
class in a moment.
To demonstrate loose coupling, let's modify the
Address
class so that it uses tight
encapsulation, shown here in a new class named
Address2
:
public class Address2 {
private String street;
private String city;
Search WWH ::
Custom Search