Why is using static helper methods in Java bad?

后端 未结 5 1643
北恋
北恋 2020-12-15 05:19

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 sayi

5条回答
  •  既然无缘
    2020-12-15 06:03

    This explanation seems to me very straight forward, and easy to understand.

    Declare utility methods as static, often makes your code easier to understand, which is a good thing.

    But, there is a serious limitation to this approach though: such methods / classes can't be easily mocked.

    So if a helper method has any external dependency (e.g. a DB) which makes it - thus its callers - hard to unit test, it is better to declare it non-static.

    This allows dependency injection, thus making the method's callers easier to unit test.

    Source: https://softwareengineering.stackexchange.com/a/111940/204271

提交回复
热议问题