The single responsibility principle

Let's understand how circular dependency can be eliminated by applying the single responsibility principle. Let's assume you are following three modules in a system:

  • Salary module
  • Employee module
  • HR module

The Salary module generates salary and sends it over email. Generating salary depends upon the Employee module. To get a few details, such as the appraisal process, and reward points the Employee module depends upon the HR module. At this moment, the dependency hierarchy will be as shown in the following diagram:

At some point in time, let's say you need email functionality in the HR module. Since email functionality is present in the Salary module, you decide to give dependency of the Salary module to the HR module. At this moment, the dependency graph looks like the following diagram:

This situation forms a circular dependency. To avoid this, you need to follow the single responsibility principle. This principle states that a module or class should hold responsibility of a single part of the functionality. That module or class should take total ownership of that functionality and must be encapsulated entirely. All services provided by the module must not deviate from the main functionality.

In our case, the Salary module not only generates salary, but sends emails, too. This is a violation of the single responsibility principle. When a single module performs more than one responsibility, there's a chance of poor dependency management, which may result in either:

  • Code duplication: You may write similar and common functionalities in multiple modules. For example, in this case, you may write an email sending functionality in the HR module to avoid circular dependency, but will end up with code duplication, which raises maintenance problems later on.
  • Circular dependency: As we have seen in the preceding case.

You need to write a separate module called the Utility module and put the email sending functionality in that. After you have refactored this code, both the HR module and the Salary module are now dependent on the Utility module. This is how circular dependency can be removed: by following the single responsibility principle.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.106.233