如果多个类包含相同的错误检查代码,我是否应该将其提取到新的类中?

huangapple go评论92阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年4月7日 15:54:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/61075272.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定