虽然这个论坛上有很多很好的例子,其中包含耦合和内聚的例子,但我正在努力将它完全应用到我的代码中。我可以识别代码中可能需要更改的部分。是否有任何 Java 专家能够查看我的代码并向我解释哪些方面是好的和坏的。我完全不介意自己改变它。只是很多人似乎彼此不同意,我发现很难真正理解要遵循的原则......
4 回答
首先,我想说,你得到如此不同答案的主要原因是,随着时间的推移,这确实成为一门艺术。您得到的许多意见并没有归结为严格的规则或事实,更多的是归结为一般经验。这样做 10 到 20 年后,你开始记住你做过哪些导致疼痛的事情,以及你是如何避免再次做这些事情的。许多答案适用于某些问题,但个人的经验决定了他们的意见。
在您的代码中,我真的只有一件非常大的事情要改变。我会考虑研究所谓的命令模式。这方面的信息应该不难在网络上或在 GoF 书中找到。
主要想法是您的每个命令“添加子”、“添加父”成为一个单独的类。单个命令的逻辑包含在一个易于测试和修改的小类中。然后应该“执行”该类以从您的主类中完成工作。这样,您的主类只需要处理命令行解析,并且可能会丢失大部分关于 FamilyTree 的知识。它只需要知道哪些命令行映射到哪些 Command 类并启动它们。
那是我的2美分。
In short:
Cohesion in software engineering, as in real life, is how much the elements consisting a whole(in our case let's say a class) can be said that they actually belong together. Thus, it is a measure of how strongly related each piece of functionality expressed by the source code of a software module is.
One way of looking at cohesion in terms of OO is if the methods in the class are using any of the private attributes.
Now the discussion is bigger than this but High Cohesion (or the cohesion's best type - the functional cohesion) is when parts of a module are grouped because they all contribute to a single well-defined task of the module.
Coupling in simple words, is how much one component (again, imagine a class, although not necessarily) knows about the inner workings or inner elements of another one, i.e. how much knowledge it has of the other component.
Loose coupling is a method of interconnecting the components in a system or network so that those components, depend on each other to the least extent practically possible…</p>
In long:
I wrote a blog post about this. It discusses all this in much detail, with examples etc. It also explains the benefits of why you should follow these principles. I think it could help...
我可以推荐 Alan 和 James 的书Design Patterns Explained -- A new perspective on object-oriented design (ISBN-13: 978-0321247148):
这是一本关于has-a和is-a决策的好书,包括面向对象设计中的内聚和耦合。
耦合定义了每个组件依赖于系统中其他组件的程度。给定两个组件 A 和 B,如果 A 更改,B 中的代码必须更改多少。内聚度定义了单个软件组件的各种功能的连贯性或强相关性的度量。它指的是类的作用。低凝聚力意味着班级会采取各种各样的行动,而不是专注于应该做什么。高凝聚力意味着班级专注于它应该做的事情,即只关注与班级意图相关的方法。注意:好的 API 表现出松耦合和高内聚。应始终避免的一种特别令人讨厌的紧密耦合形式是具有两个直接或间接相互依赖的组件,即依赖循环或循环依赖。 http://softwarematerial.blogspot.sg/2015/12/coupling-and-cohesion.html