重构 - 单元测试 - 遗留代码中的设计困境
当您处理遗留代码时,您如何解决这个问题
- 您处理的类设计不佳,需要一些严重的设计更改
- 您处理的类大多是紧密耦合的
- 您没有足够的单元测试来进行重构
- 您没有添加新的单元测试,因为设计很糟糕,无论如何你都会改变它
- 你不能轻易改变设计,因为
- 紧密耦合,没有足够的单元测试 - 东西可能真的是错误的,因为它需要同时为多个类进行新设计,而没有任何安全网。
你从哪里开始?你如何解决这个问题?
How do you tackle this problem when you are dealing with legacy code
- Classes you deal with is not well designed, requires some serious design changes
- Classes you deal with mostly tightly coupled
- You don't have enough unit tests to do refactoring much
- You don't add new unit tests because design is bad and you are going to change it anyway
- You can't change the design that easily because
- Tight coupling, not enough unit tests - stuff can really wrong as it requires a new design for multiple classes at the same time without any safety nets.
Where do you start? How do you attack to the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
先有鸡还是先有蛋的问题。
如果由于大腿耦合而无法编写一些像样的单元测试,更好的方法可能是自上而下工作。
如果您还没有集成、系统和/或 GUI 测试,那么这将是您在开始创建单元测试之前创建它们的一个很好的理由。一旦你把它们准备好,你就可以开始重构代码来创建像样的单元测试,并且仍然相当有信心你的全面测试将发现你最明显的错误。
请注意,在我个人看来,这些测试用例应该这样创建,一旦您准备好开始创建单元测试并重构代码,就不必更改它们。
有关此主题的必读文章是 Michael Feathers 的有效处理遗留代码。
A Chicken and Egg problem.
If it's not possible to write some decent unit tests because of thight coupling, a better approach might be to work from the top down.
If you don't already have Integration, System and or GUI tests, this would be a good reason to create them before you start creating unit tests. Once you have them in place, you can start refactoring the code to create decent unit tests and still be fairly confident that your all-compassing tests will catch your most obvious mistakes.
Note that in my personal opinion, these testcases should be created as such that they should not have to be altered once you are ready to start creating unit tests and refactoring your code.
A must read on this subject is Working Effectively with Legacy Code by Michael Feathers.
您首先要确保不会更改代码的行为。
如果您编写断言代码当前行为方式的单元测试,那么您可以对代码进行更改并检查测试是否仍然通过,如果通过,则代码行为没有改变。
然后您可以根据需要重构代码。当您重构设计时,您也会重构测试,但不要更改它们所做的断言。
You first want to make sure you don't change the behaviour of the code.
If you write unit tests which assert the way that the code currently behaves then you can make changes to the code and check that the tests still pass, if they do then the code behaviour hasn't changed.
You can then refactor the code however you like. When you refactor the design you refactor the tests as well, but don't change the assertions they make.