I am stuck at some random problem based on Coupling.
A class Candidate with various methods for getting information about the candidate. One of such methods is
getScore()
score obtained by the candidate. Suppose we have another class CompScience that stores the details of candidates who are eligible to apply for the admission in Computer Science stream. Class CompScience has a method namedisEligibleToApply()
which returns true if a candidate has score more than 350. One of the structure for this methodisEligibleToApply(
) is given below:
boolean isEligibleToApply(Candidate c) {
integer score = c.getScore();
Return true if Score is more than 350
}
In this case, if we change the getScore()
method of Candidate class in some way (for example, by renaming it), we might also have to change the isEligibleToApply()
method of CompScience class.
If I change the name of method getScore(), then it should also be changed in isEligibleToApply() method. This always happens as we change the names and wikipedia suggests this as content-coupling.
Is there any way that no changes are possible in isEligibleToApply() method and code is made loose coupled. I searched about loose coupling and got some suggestions to use interfaces to make the code loose coupled.
Any hints/suggestions ?
The way to address this problem is to extract public interface from your Candidate
class. This interface will declare the API contract that should never change in breaking manner. Even if you decide to rename or remove getScore
method from the implementation, interface will force you to provide implementation of the old method for compatibility.
Needless to say, CompScience
in this case will take interface as an argument for isEligibleToApply
.
And one more note. This approach makes sense only when Candidate
and CompScience
are exposed as part of your public API. Or, at least, they are public within your project.
In some cases, such as inside a private module, it doesn't make sense to decouple things just for the sake of it.