Cohesion and low coupling

1 ) Cohesion

Cohesion refers to how focused a class or a module is. High cohesion refers to a well focused class or module, whereas low cohesion refers to a class or module that doesn’t have a well-defined responsibility. Such modules or classes might perform multiple actions, which could have been assigned to separate classes.

Imagine a book editor who is supposed to edit book content, manage the book printing process, and reach out to new authors for new book ideas. Let’s define this editor by using a class, say, Editor:

The preceding example creates a highly cohesive class, Editor. Highly cohesive classes are easy to use. In the preceding example, class Editor provides a one-stop solution for all editing tasks. Highly cohesive classes are also easy to maintain and reuse; whenever you need to add or modify any editing-related process, you know which class you need to refer to: class Editor.

Note : Well-designed applications aim for highly cohesive classes and modules.

2) Coupling

Coupling refers to how much a class or module knows about other classes or modules. If a class—say, Editor—interacts with another class—say, Author—by using its interface (public methods), then classes Editor and Author are loosely coupled. But if class Editor can access and manipulate Author by using its nonpublic members, these classes are tightly coupled.

The terms low coupling and loose coupling refer to the same concept. They are often used interchangeably.

The modified class Editor is tightly coupled with class Author. The method clear- EditingDoubts in class Editor accesses the nonpublic member skypeId of class Author:

What happens, say, if a programmer changes the name of the variable skypeID in class Author to skypeName? The code of class Editor won’t compile. As long as the public interface of a class remains the same, it’s free to change its implementation details. In this case, the name of instance variable skypeID forms part of Author’s implementation details. One suggested solution is to use the public method getSkypeID() in class Editor (changes in bold):

Last updated