我们如何实现编写可重用和模块化的代码
我们如何实现在企业代码中编写可重用和模块化的代码。入门的基础知识是什么
How we can achieve writing reusable and modular code in an Enterprise code. What are the basics to get started
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编写模块化代码是一门编程艺术。
在企业产品中,编写可重用代码是使产品长期可靠、可测试和可维护的关键。模块化和可重用的代码是任何标准产品的核心。
让我们举一个例子来了解如何将现有代码转换为更加模块化和可重用的代码。
假设产品中存在一种方法/逻辑,它采用正整数的一维数组作为输入并计算所有元素的总和。
该方法实际上是评估用户在给定年份的总交易金额。考虑到这是最初的业务需求,因此代码是以这种方式编写的。
现在,假设有一个新的业务需求,想要评估上半年的用户交易情况。你将如何实现它?也许再写一个可以评估上半年的方法。正确的。让我们看看这个方法是什么样的。
很酷,我们已经做到了。 :)
但是否可以通过其他方式来完成,或者可能是更好的方式。让我们看看。
我们实际上可以编写一个更通用/可重用的方法,它可以给出给定时间段内的交易总和。像这样的
现在我们可以为两个现有的需求调用这个可重用的方法。
甚至任何未来的要求,比如说一月份,我们都需要简单地调用像这样的相同方法
为什么我们正在寻找更好的方法?可能是为了适应未来的需求并减少代码行。
我们取得的成果:
谢谢!
Writing modular code is an art of programming.
In Enterprise products, writing reusable code is a key to make your product reliable, testable and maintainable for long run. Modular and reusable code sits at the very heart of any standard product.
Let's take an example to understand how we can convert and existing code into more modular and reusable code.
Let say there exist a method/logic in the product which take an 1-D array of positive integers as input and evaluate the sum of all the elements.
This method actually evaluates the total transaction amount of a user in a given year. Consider that this was the initial business requirement and hence code has been written in such a fashion.
Now, let's say a new business requirement has come, which wants to evaluate the user transactions of a the first half of the year. How you are going to achieve it? Maybe writing one more method which can evaluate for first half of the year. Correct. Let see how that method looks like.
Cool we have done it. :)
But can it be done in any other way, or may be a better way. Let see.
We can actually write a more generic/reusable method which can give the sum of transactions for a given period. Something like this
Now we can call this reusable method for both of the existing requirement.
And even any future requirements, lets say for the month of January, we need to simply call same method like this
Why we are looking for better way? may be to accommodate future requirements and reducing line of code.
What we achieved:
Thanks!