我正在开发一个支持 Spring 的 Web 项目,其中我们有多个 Controller 。最近我与高级开发人员讨论了 Controller 中应该包含哪些代码。
其中一些据说是为了让 Controller 轻量化;只有调用方法才应该进入 Controller 内部。即使只有 3 行处理,也将它们分成单独的方法并从 Controller 中调用它们,如下所示
public ModelAndView offersMapView(HttpServletRequest request, HttpServletResponse response) {
Map<String, Object> contentMap = getServiceLocator().getHyperLocalService().getOffersHubContents(searchPostcode, gmapKey, ip);
return getViewGenerator().generateOffersHubMapView(brand, contentMap);
}
其中generateOffersHubMapView(brand, contentMap)方法仅包含2行代码
public ModelAndView generateOffersHubMapView(Brand brand, Map<String, Object> contentMap) {
ModelAndView mv = POGAModelandView.createWebModelAndView(brand, WLConstants.__HUB_OFFERS);
mv.addAllObjects(contentMap);
return mv;
}
我的观点是,在我们有大量代码处理行之前,创建单独的 View 生成器方法的 2 行代码并不好。
相反的观点是创建单独的方法来保持层之间的隔离。
请问社区他们认为更好的方法是什么?如果可能的话,您能否提供引用资料来支持您的陈述?
最佳答案
没有任何规则表明这一点
Even if there are only 3 lines of processing, make them separate methods
我认为,如果没有正当理由,每三行就分割一次只会让事情变得复杂。专注于可重用性和可读性。如果单个方法中有可重用的代码,请将其拆分。如果您的方法太长并且做了很多事情,请将其拆分。阅读 https://stackoverflow.com/questions/20981/how-many-lines-of-code-is-too-many 上的讨论和https://stackoverflow.com/questions/903754/do-you-still-limit-line-length-in-code .
我个人认为,generateOffersHubMapView 方法 split 在您的示例中没有多大意义。
关于Java Controller 需要什么代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8830248/