如何在企业代码中实现可重用和模块化代码的编写。入门的基本知识是什么?
发布于 2022-03-13 15:08:06
编写模块化代码是一门编程艺术。
在企业产品中,编写可重用代码是保证产品可靠、可测试和长期可维护的关键。模块化和可重用代码处于任何标准产品的核心位置。
让我们举一个例子来了解如何将现有的代码转换为更模块化和更可重用的代码。
假设乘积中存在一个方法/逻辑,它以一个一维正整数数组作为输入,并计算所有元素的和。
// Method signature
// Business: Each element of array holds the amount of total transaction done by the user on each day for a year. Hence the array length is 365.(ignore leap year)
int sumYear (int [] A) {
// logic
sum of elements from index 0 to last index (364) of array A
}此方法实际上评估给定年份中用户的总事务量。考虑到这是最初的业务需求,因此代码就是以这种方式编写的。
现在,假设出现了一个新的业务需求,它希望评估上半年的用户事务。你将如何实现它?也许还可以再写一种方法来评估上半年的情况。对,是这样。让我们看看这个方法是什么样子的。
// Method signature
// Business: Each element of array holds the amount of total transaction the user has done on each day for a year. Hence the array length is 365.
int sumHalfYear (int [] A) {
// logic
sum of elements from index 0 to last index (182) of array A (ignore leap year)
}太酷了,我们做到了。:)但能否以任何其他方式进行,或可能是一种更好的方法。让我看看。
我们实际上可以编写一个更通用/可重用的方法,它可以给出给定时期内事务的总和。就像这样
// Method signature
// Business: Each element of array holds the amount of transaction the user has done on each day for a year. Hence the array length is 365.
// startIndex: Starting index to consider for evaluation
// endIndex: Ending index to consider for evaluation
int sum (int [] A, int startIndex, int endIndex) {
// logic
sum of elements from index "startIndex" to "endIndex" of array A (ignore leap year)
}现在,我们可以对现有的两个需求调用这个可重用的方法。
// Method signature
// Business: Each element of array holds the amount of transaction the user has done on each day for a year. Hence the array length is 365.
int sumYear (int [] A) {
//sum of elements from index 0 to last index (364) of array A
return sum(A, 0, 364);
}
// Method signature
// Business: Each element of array holds the amount of transaction the user has done on each day for a year. Hence the array length is 365.
int sumHalfYear(int[] A) {
//sum of elements from index 0 to last index (182) of array A (ignore leap year)
return sum(A, 0, 182);
}即使是未来的任何需求,比如说一月份,我们也需要调用类似的方法
// Method signature
// Business: Each element of array holds the amount of transaction an user has done on each day for a year. Hence the array length is 365.
int sumJanuray (int [] A) {
//sum of elements from index 0 to last index (30) of array A
return sum(A, 0, 30);
}为什么我们要寻找更好的方法?可能是为了适应未来的需求和减少代码行。
我们所取得的成就:
由于业务逻辑Usability
,较高的
谢谢!
https://stackoverflow.com/questions/71458039
复制相似问题