我们如何实现编写可重用和模块化的代码



我们如何在企业代码中实现编写可重用的模块化代码。开始的基础是什么

编写模块化代码是一门编程艺术。

在企业产品中,编写可重复使用的代码是使您的产品长期可靠、可测试和可维护的关键。模块化和可重复使用的代码是任何标准产品的核心。

让我们举一个例子来了解如何将现有代码转换为更模块化和可重用的代码。

假设乘积中存在一种方法/逻辑,它以正整数的一维数组为输入,并计算所有元素的和。

// 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);
}

为什么我们在寻找更好的方式?可能是为了适应未来的需求并减少代码行。

我们取得的成就:

  1. 更高的可用性
  2. 更高的可维护性
  3. 较小的代码行
  4. 由于业务逻辑修改,未来不太可能出现回归

谢谢!

最新更新