为什么在 Java 中使用静态辅助方法不好?

Why is using static helper methods in Java bad?(为什么在 Java 中使用静态辅助方法不好?)
本文介绍了为什么在 Java 中使用静态辅助方法不好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我之所以问,是因为我正在尝试使用一个不允许您模拟静态方法的模拟框架 (Mockito).调查它,我发现很多博客文章说你应该尽可能少地使用静态方法,但我很难理解为什么.特别是为什么不修改全局状态并且基本上是辅助方法的方法.例如,我有一个名为 ApiCaller 的类,它有几个静态方法.静态方法的目的之一是执行 HTTP 调用,处理我们的服务器可能返回的任何自定义问题(例如用户未登录)并返回响应.为了简化,类似:

I'm asking because I'm trying to use a mocking framework (Mockito) which does not allow you to mock static methods. Looking into it I've found quite a few blog posts saying that you should have as few static methods as possible, but I'm having difficulty wrapping my head around why. Specifically why methods that don't modify the global state and are basically helper methods. For instance I have a class called ApiCaller that has several static methods. One of the static method's purpose is to execute an HTTP call, deal with any custom issues our server might have returned (ex. user not logged in) and return the response. To simplify, something like:

public class ApiCaller {
...
   public static String makeHttpCall(Url url) {
        // Performs logic to retrieve response and deal with custom server errors
        ...
        return response;
   }
}

要使用它,我只需调用 ApiCaller.makeHttpCall(url)现在我可以轻松地将其设为非静态方法,例如:

To use this all I have to do is call ApiCaller.makeHttpCall(url) Now I could easily make this a non static method like:

public class ApiCaller {
...
   public String makeHttpCall(Url url) {
        // Performs logic to retrieve response and deal with custom server errors
        ...
        return response;
   }
}

然后使用此方法调用 new ApiCaller().makeHttpCall() 但这似乎是额外的开销.谁能解释为什么这很糟糕,以及是否有更好的解决方案使方法成为非静态方法(除了删除关键字之外),以便我可以使用模拟框架删除这些方法?

and then to use this method call new ApiCaller().makeHttpCall() but this just seems like extra overhead. Can anyone explain why this is bad and if there is a better solution to making the methods non static (other than just removing the keyword) so that I can stub out these methods using the mocking framework?

谢谢!

推荐答案

静态方法的问题是当它们与您尝试测试的系统无关时,它们很难伪造.想象一下这段代码:

The problem with static methods is they're very hard to fake when they're not relevant to the system you're trying to test. Imagine this code:

public void systemUnderTest() {
    Log.connectToDatabaseForAuditing();
    doLogicYouWantToTest();
}

connectToDatabaseForAuditing() 方法是静态的.您不在乎此方法对您要编写的测试有什么作用.但是,现在要测试此代码,您需要一个可用的数据库.

The connectToDatabaseForAuditing() method is static. You don't care what this method does for the test you want to write. But, to test this code now you need an available database.

如果它不是静态的,代码将如下所示:

If it were not static the code would look like this:

private Logger log; //instantiate in a setter AKA dependency injection/inversion of control

public void systemUnderTest() {
    log.connectToDatabaseForAuditing();
    doLogicYouWantToTest();
}

如果现在没有数据库,您的测试将是微不足道的:

And your test would be trivial to write without a database now:

@Before
public void setUp() {
    YourClass yourClass = new YourClass();
    yourClass.setLog(new NoOpLogger());

}

//.. your tests

想象一下当方法是静态的时尝试这样做.除了修改记录器以拥有一个名为 inTestMode 的静态变量,您在 setUp() 中将其设置为 true 以确保它不会'不连接到数据库.

Imagine trying to do that when the method is static. I can't really think of a way except for modifying the logger to have a static variable called inTestMode that you set to true in the setUp() to make sure it doesn't connect to a database.

这篇关于为什么在 Java 中使用静态辅助方法不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Sending a keyboard event from java to any application (on-screen-keyboard)(将键盘事件从 java 发送到任何应用程序(屏幕键盘))
How to make JComboBox selected item not changed when scrolling through its popuplist using keyboard(使用键盘滚动其弹出列表时如何使 JComboBox 所选项目不更改)
Capturing keystrokes without focus(在没有焦点的情况下捕获击键)
How can I position a layout right above the android on-screen keyboard?(如何将布局放置在 android 屏幕键盘的正上方?)
How to check for key being held down on startup in Java(如何检查在Java中启动时按住的键)
Android - Get keyboard key press(Android - 获取键盘按键)