如何避免给定代码中的耦合类型?

How to avoid the type of coupling in the given code?

我遇到了一些基于 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 named isEligibleToApply() which returns true if a candidate has score more than 350. One of the structure for this method isEligibleToApply() is given below:

boolean isEligibleToApply(Candidate  c) {
integer score = c.getScore();
Return true if Score is more than 350
}

在这种情况下,如果我们以某种方式更改 Candidate class 的 getScore() 方法(例如,通过重命名它),我们可能还必须更改 isEligibleToApply() CompScience 方法 class.


如果我更改方法 getScore() 的名称,那么它也应该在 isEligibleToApply() 方法中更改。这总是在我们更改名称时发生,维基百科将其建议为内容耦合。

有没有什么方法可以使 isEligibleToApply() 方法和代码松散耦合。我搜索了松散耦合并得到了一些使用接口使代码松散耦合的建议。

有 hints/suggestions 吗?

解决此问题的方法是从您的 Candidate class 中提取 public 接口。此接口将声明 API 合同,该合同永远不应以破坏方式更改。即使您决定重命名或从实现中删除 getScore 方法,接口也会强制您提供旧方法的实现以实现兼容性。

不用说,CompScience 在这种情况下会将接口作为 isEligibleToApply 的参数。

还有一张纸条。只有当 CandidateCompScience 作为 public API 的一部分公开时,这种方法才有意义。或者,至少,它们在您的项目中 public。

在某些情况下,例如在私有模块内部,仅仅为了它而解耦是没有意义的。

当你改变方法时,你不可避免地需要替换使用方法的位置。你可以做一些事情,比如写一个 CandidateScoreCalculator class,它可能有一个叫做 getScore(Candidate c); 的方法,你可以在 isEligibleToApply() 方法中使用它,但是当 getScore() 方法已更改您必须在使用该方法的位置也进行更改。