内聚和耦合

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

什么是内聚性

内聚是指一个模块的内部功能相互关联的紧密程度,执行某个特定的任务或相关任务组的模块是具有高内聚性的,而没有核心功能只是将大量功能凑到一起的模块具有低内聚性。

什么是耦合性

耦合是指模块 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))
	
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值