英文:
If multiple classes contain same code for error checking should I extract it into new class?
问题
我正在处理一个项目,其中有几个类在其某个方法中具有相同的错误检查。即使这段代码不到10行,我是否应该将这个错误检查提取到另一个类中?
举个例子,所有类中的方法都接收相同的对象,并以不同的方式对其进行处理。我最初在检查对象是否为空,然后从对象中获取一个列表来查看其是否为空。我在考虑提取这些检查,因为我听说每个方法应该只做一件事。
英文:
I'm working on a project where several classes have the same error checking in one of their methods. Should I extract this error checking into a different class, even though it's only under 10 lines of code?
As an example, the method in all the classes take in the same object and does something different with it, I'm checking initially if that object is null and then getting a list from the object to see if it's empty. I was thinking of extracting these checks because I've heard each method should only do one thing.
答案1
得分: 0
作为一个经验法则,你应该总是在代码库中提取相同的功能,并在需要时重复使用它们,而不是复制粘贴。如果你必须改变验证逻辑,如果它在多个方法中出现,你将不得不进行"手术刀式重构"。
在进行空值检查和确定集合是否为空方面,有一些经过实战考验的开源库可供使用。在自己实现之前先进行一些调查。这里有一个来自Guava库的示例。
英文:
As a general rule of thumb, you should always extract identical functionality in your codebase and reuse them instead of copying & pasting over. If you have to change the validation logic you'll have to do a shotgun surgery if it is appearing in multiple methods.
There are some battle-tested open-source libraries available for null checking and determining if collections are empty. Look around before implementing your own. Here is an example from the Guava library.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论