0% completed
Coupling refers to how closely connected different modules, classes, or methods are to each other.
In software design, we aim for low coupling, meaning that classes and components should be as independent from each other as possible. High coupling, on the other hand, means that classes are tightly dependent on one another, making it harder to change or reuse parts of the system.
Let’s think of a general example. Imagine you have a TV and remote that only work together. The remote can only control this specific TV, and the TV can’t be operated by any other remote. This represents high coupling because the two devices are tightly connected, and you can't easily swap one out without the other.
Now, imagine you have a universal remote that can control multiple devices, and a TV that works with any remote. This is an example of low coupling, where the devices are more independent, flexible, and interchangeable.
Let’s start with an example where the Student
class is responsible for both student information and database operations. This creates high coupling because the Student
class is tightly dependent on the database functionality.
Here, the Student
class handles both the student’s information (like getStudentId
and setStudentId
) and the database interaction (save()
method). This creates high coupling, as any change to the database logic will require changes to the Student
class as well.
To improve the code and reduce coupling, we can move the database-related logic into a separate class, say DatabaseManager
. The Student
class will then focus on handling student data, and the database operations will be managed by the DatabaseManager
class. This leads to low coupling and follows the Single Responsibility Principle (SRP).
Now, the Student
class no longer handles database logic directly. It delegates the responsibility to the DatabaseManager
. This reduces coupling and ensures that each class focuses on a single responsibility:
Reducing coupling makes it easier to follow the Single Responsibility Principle. Here’s why:
By splitting the responsibilities (like student management and database operations) into different classes, we maintain low coupling and follow SRP. This ensures that each part of the system is focused and independent, making future changes much easier.