英文:
Java pattern for refactoring abused MVC controller class
问题
以下是翻译好的内容:
我继承了这个已经存在大约10年历史的意大利面后端服务代码库,它是用Java和maven编写的。
原始作者将大量内容放在一个RequestController类中,其中包含诸如
processPostRequestV1
processPostRequestV2
....
processPostRequestV6
以及
getRequestV1
getRequestV2
...
getRequestV6
还有所有的实用函数都在这一个类中。
它们都读写同一个数据库(谢天谢地),但是这个类几乎依赖了20个相关的bean和3000行代码。
我在思考,重构这种类型的代码的最佳模式是什么,它似乎是一个编排层,但是应该使用什么模式来管理它的版本?(其中一些版本甚至没有意义,例如来自旧版本的代码与新版本共享代码,使用新的依赖项等,但那是另外一回事)
在MVC模式中,控制器应该从模型/业务层收集/更新数据,这与这个RequestController类正在做的事情非常相似,我在这里漏掉了什么?
英文:
So I inherited this spaghetti back end service code base which has probably 10 years of history, it is written in Java and maven.
the original author put tons of stuff in a RequestController class, which has functions like
processPostRequestV1
processPostRequestV2
....
processPostRequestV6
and
getRequestV1
getRequestV2
...
getRequestV6
and all the utility functions in just this one class.
they all read and write to the same DB (thank god), but this class has close to 20 dependent beans and 3000 lines of code.
I am wondering, what is the best pattern for refactoring this kind of code, it seems to be a orchestration layer, but what pattern should be used to manage the versions for it? (some of the versions don't even make sense, e.g. code from older version is sharing code with new one, using new dependencies etc, but that is a different matter)
In a MVC pattern, controller is supposed to gather/update data from the Model/Business layer which looks exactly like what this RequestController class is doing, what am I missing here?
答案1
得分: 1
首先... 你是否针对该类编写了测试?你信任这些测试吗?如果没有,请不要进行重构。先编写测试。
因为重构意味着
> 在不改变代码行为的情况下改变其结构。
如果你有测试,我会创建新的结构,并将 RequestController 类的方法改为委托给新的结构。
也许新的结构类似于清洁架构、BCE(边界-控制器-实体)或六边形架构。
在清洁架构的情况下,RequestController 将通过用例的输入边界传递请求模型,并传递一个输出边界给用例,请求控制器将对其进行适配以返回结果。
英文:
First of all... Do you have tests for that class? Test that you trust? If not, do not refactor. Write the tests first.
Because refactoring means
> Change the structure of code without it's behavior
If you have tests I would create a the new structure and change the RequestController class's methods to delegate to the new structure.
Maybe the new structure is something like the clean architecture, the BCE (boundary controller entity) or the hexagonal architecture.
In case of the clean architecture. The RequestController will pass request models through the use case's input boundary and pass the use case an output boundary that the request controller will adapt to return the result.
Take a look at https://softwareengineering.stackexchange.com/questions/388578/clean-architecture-is-the-input-boundary-necessary
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论