Java utils 类、静态方法与注入 utils 类 [英] Java utils class, static methods vs injecting the utils class

查看:118
本文介绍了Java utils 类、静态方法与注入 utils 类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你们如何创建 utils 类?有标准的方法吗?

How do you guys create utils classes? Is there a standard way?

就像标题所说的那样,您可以使用以下内容:

Like the headline says you can either have something like:

public class Utils {

   public static method1(){...}

   public static method2(){...}
...
}

并通过调用 Utils.method1() 来使用它,但是那样,当你为使用这个 utils 类的类编写单元测试时,你不能模拟静态方法,所以如果它们有错误单元测试将失败.

and use it by calling Utils.method1(), but that way, when you write unit tests for the class that uses this utils class you cant mock the static methods so if they have a bug the unit test will fail.

或者,您可以使用这些 utils 在类的构造函数中提供 utils 类的实例,这样您就可以在单元测试中模拟它,但对我来说,将 utils 类的实例提供给每个人看起来很尴尬使用它的类,并且通常必须创建一个 utils 类的实例.我的意思是,如果我们有使用 Utils 类中的方法的 A 类,我们可以这样做:A a = new A(new Utils());

Or, you can give an instance of the utils class in the constructor of the class using these utils and that way you can mock it in unit tests, but to me it looks very awkward giving an instance of a utils class to every class that uses it, and having to create an instance of a utils class in general. I mean something like if we have class A that uses a method from the Utils class we can do: A a = new A(new Utils());

有没有办法同时实现这两个目标?或者至少是行业标准的东西?还是我没想到的其他方式?

Is there a way that achieves both? Or at least something that is standard in the industry? Or another way that I didnt think of?

推荐答案

通常,您可以(也不必)为实用程序方法编写静态方法,这些方法不需要模拟或切换到它们的不同实现.
某些处理可能不需要模拟或实现切换.所以让它们成为静态实用方法是可以接受的.
以数学函数为例,例如计算数字的平方根.您不需要模拟它或切换到另一个实现.
所以使用静态方法应该不会导致任何问题.

Generally you may (and not have to) write static methods for utility methods that you don't need to mock or to switch to different implementation of them.
Some processing may require no mock or implementation switching. So make them static utility methods is acceptable.
Take for example a Math function such as computing the square root of a number. You should not need to mock it or to switch to another implementation.
So using a static method should not cause any issue.

对于不知道是否需要模拟/切换到其他实现的情况,我认为您应该支持实例方法,因为它更灵活.

For cases where you don't know if you need to mock/switch to other implementations, I think that you should favor instance methods as it is more flexible.

这篇关于Java utils 类、静态方法与注入 utils 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆