Spring Boot 接口声明静态方法

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

Spring boot interface declaring static method

问题

我在考虑一个纯函数,我应该将它声明为Spring Boot应用程序中的静态方法还是实例方法。因为我认为这个函数的最佳位置是实体的Service类,在将其声明为静态方法的情况下,它应该放在接口中,但我担心这不符合最佳实践。我在下面的代码中添加了类似的函数。

public boolean isDone(String x) {
   return x.equals(EntityState.DONE);
}
英文:

I'm wondering about one pure function, should I declared it as static method or as instance method in Spring boot app. Because I think the best place for this function is the Service class of the entity, in the case of declaring it as static, it should be placed in the interface, but I have some concerns that this is not following the best practices. I added the similar function to mint below.

public boolean isDone(String x) {
   return x.equals(EntityState.DONE);
}

答案1

得分: 1

因为这似乎是在检查实体的状态,我更倾向于将这个方法添加为实体类的实例方法。

实际上并不清楚这个接口是否有其他用途,或者它是否只是为了托管这个静态方法而创建的,因此不清楚有什么好处。如果有某种原因不希望将方法添加到实体类中,将方法放在服务类中也可以。

最好使用枚举而不是比较字符串。你还可以通过反转顺序来提高安全性,例如:

EntityState.DONE.equals(x);

这样,如果 x 为 null,它不会抛出 NPE。

英文:

Since this seems to be checking the state of an entity, my preference would be to add this as an instance method on the entity class.

It really isn't clear if this interface has some other purpose or if it is created just to host this static method, so it isn't clear what the advantage is of having it. Putting the method on the service is ok if there is some reason to avoid adding the method to the entity class.

It would be better to use enums than to compare strings. You can also make this safer by reversing the order like

 EntityState.DONE.equals(x);

This way if x is null it doesn't throw a NPE.

huangapple
  • 本文由 发表于 2023年7月7日 04:09:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76632242.html
匿名

发表评论

匿名网友

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

确定