什么是内聚性
内聚是指一个模块的内部功能相互关联的紧密程度,执行某个特定的任务或相关任务组的模块是具有高内聚性的,而没有核心功能只是将大量功能凑到一起的模块具有低内聚性。
什么是耦合性
耦合是指模块 A 和模块 B 功能上的相关程度。如果两个模块的功能在代码层面上高度重叠,即模块之间有方法的大量互相调用,那么这两个模块就是高耦合的。在模块 A 上的任何变动都会使得 B 变化。
强耦合性不利于代码的可修改性,因为它增加了维护代码的成本,要提高代码的可修改性就应该做到代码的高内聚和低耦合。
测量内聚性和耦合性
举一个小例子来说明如何判断内聚性和耦合性。下面是模块 A 的代码:
""" Module A(a.py) - Implement functions that operate on series of numbers """
def squares(narray):
""" Return array of squares of numbers """
return pow_n(array, 2)
def cubes(narray):
""" Return array of cubes of numbers """
return pow_n(array, 3)
def pow_n(narray, n):
""" Return array of numbers raised to arbitrary power n each """
return [pow(x, n) for x in narray]
def frequency(string, word):
""" Find the frequency of occurrences of word in string as percentage """
word_l = word.lower()
string_l = string.lower()
# words in string
words = string_l.split()
count = w.count(word_l)
# return frequency as percentage
return 100.0 * count / len(words)
然后是模块 B 的代码:
""" Module B(b.py) - Implement functions provide some statistical methods """
import a
def rms(narray):
""" Return root mean square of array of numbers """
return pow(sum(a.squares(narray)), 0.5)
def mean(array):
""" Return mean of an array of numbers """
return 1.0 * sum(array) / len(array)
def variance(array):
""" Return variance of an array of numbers """
# square of variation from mean
avg = mean(array)
array_d = [(x - avg) for x in array]
variance = sum(a.squares(array_d))

本文介绍了内聚性和耦合性在代码组织中的重要性,高内聚低耦合是良好的代码设计原则。讨论了如何通过测量内聚性和耦合性来评估代码质量,并提出了提高代码可修改性的策略,包括提供显式接口、减少双向依赖、抽象出公共服务以及使用继承技术。
最低0.47元/天 解锁文章
6483

被折叠的 条评论
为什么被折叠?



