CSC/ECE 517 Summer 2008/wiki3 3 n1
Introductiion
In object-oriented system, coupling is the degree to which a class relies on other classes. Low (or loose) coupling means that a class interacts with another class through an interface and does not to be concerned with the other class's internal implementation. In other words, with low coupling, a change in one class will not require a change in the implementation of another class. Low coupling is desirable; systems with high coupling usually experience the following difficulties:
- Classes are difficult to understand when examined in isolation.
- Changing in one class create a ripple effect that requires changes in other classes.
- Codes are harder to modularize due high dependency, thus become less reusable.
In rare cases, a high coupling is desirable to achieve maximum efficiency and performance, such as codes that perform hardware intensive functions, i.e. batch I/O. However in general the cost of reduced performance is outweighed by the benefits of reusable components and quicker software development that result from low coupling.
Minimizing coupling
To avoid the pitfalls of high coupling in a system mentioned earlier, classes should be designed in such a way that there is separation of responsibilities; they should be written in such a way that changing one class is not likely to require change in other classes. The following guidelines help to minimizing coupling:
- Design classes so that variables have the widest possible type (interface) rather than the narrowest type.
- Code to interfaces, not classes. Wherever possible write code so that objects are referred to by the interfaces they implement instead of by the concrete class to which they belong.
- Encapsulate the concepts that vary.
- Divide different responsibilities among different objects.
- Apply Observer pattern when an object must be notified of an action or event performed by another object.
- Apply Mediator pattern where complexity of communications between classes becomes an issue. Mediator provides a unified interface for a set of interfaces in a sub system, allowing objects to communicate with mediator instead of each other.
- Apply Law of Demeter; a given object should assume as little as possible about the structure or properties of others
- The less arguments past to a class, the better.
- Encapsulate chains of routine calls that involve multiple classes into one class. So a given class only deals with one class instead of many.