英文:
Is correct to have private method in service layer?
问题
我正在使用Java和Spring Framework开发一个服务,我在服务层有业务逻辑,但我需要遵守单一职责原则,而且我需要进行许多验证和其他操作。目前,我在服务类中有一个私有方法来执行这些操作,但我认为方法太多了,是否正确将这些方法放在服务类中,还是更好地放在自定义包中的另一个类中?
英文:
I am developing a service using Java and Spring Framework, I have business logic at the service layer, but I need to respect the single responsibility and I do a lot of validations and other things, currently, I have a private method the service class to do these things, but I think there are many methods, is it correct to have these methods in service or is it better to have it in another class in custom package?
答案1
得分: 1
以下是要翻译的内容:
这是一个来自https://howtodoinjava.com/java9/java9-private-interface-methods/的简单示例,演示了在哪些情况下您可能需要在您的服务中使用一些私有方法。
import java.util.function.IntPredicate;
import java.util.stream.IntStream;
public interface CustomCalculator
{
default int addEvenNumbers(int... nums) {
return add(n -> n % 2 == 0, nums);
}
default int addOddNumbers(int... nums) {
return add(n -> n % 2 != 0, nums);
}
private int add(IntPredicate predicate, int... nums) {
return IntStream.of(nums)
.filter(predicate)
.sum();
}
}
在这种情况下,添加特定的私有方法"add"并不是不合逻辑的,因为它在您的公共方法中使用,因此并不是一种反模式。
问题可能出在测试这些私有方法上。
相比之下,您不应该在服务中拥有过多的私有方法。如果是这样,您应该将这些私有方法分离到一个辅助类中,并将它们作为服务的依赖项添加进去。这样,您可以将它们与服务分开进行测试。
英文:
Here is a simple example from https://howtodoinjava.com/java9/java9-private-interface-methods/ that demonstrates in which cases you could need somes private methods in your service.
import java.util.function.IntPredicate;
import java.util.stream.IntStream;
public interface CustomCalculator
{
default int addEvenNumbers(int... nums) {
return add(n -> n % 2 == 0, nums);
}
default int addOddNumbers(int... nums) {
return add(n -> n % 2 != 0, nums);
}
private int add(IntPredicate predicate, int... nums) {
return IntStream.of(nums)
.filter(predicate)
.sum();
}
}
In this case it's not illogical to add this specific private method "add" because it serves in your public methods so it's not an anti-pattern at all.
The problem could be in testing these private methods in tests.
By contrast, you shouldn't have too much private methods in service. If so, you should separates these privates methods in an helper class and add them as a dependence in the service. This way, you could test them separately of the service.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论