使用TDD方法并避免Java静态方法 [英] Using TDD approach and avoiding Java static methods

查看:58
本文介绍了使用TDD方法并避免Java静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚收到有关作业应用程序Java编码练习的一些反馈.他们不喜欢解决方案和反馈中提到的两个问题(我非常感激,因为给出的反馈非常罕见):

I just got some feedback about a job application Java coding exercise. They did not like the solution and two problems where stated in the feedback (which I'm very grateful for as it's very rare feedback is given):

  • 显然我没有使用TDD方法.
  • 我过度使用了静态方法,我知道静态方法是反面向对象的,但是我只在验证和util类型方法中使用了它们.

这里有两个问题:

不使用TDD方法的可能的迹象是什么?

What are the possible tell-tale signs of not using TDD approach?

哪种编码样式或模式可以替代静态方法?

What coding style or patterns can be an alternative to static methods?

在前两个回答之后,我还有另一个问题.

Following the first two responses I have another question.

您是否同意,仅当静态方法限制了代码的可测试性时,使用静态方法才是坏方法,而不是在它们自身中带来不好的结果.

Do you agree that using static methods is only bad when it limits the testability of your code and not in them selves bad.

因此,如果静态方法不限制我的代码的可测试性,请回到我的工作申请练习解决方案,使用起来仍然不好吗?我的验证方法非常简单'Validator.notNull(p,"paramName")'现在为什么我要模拟它?

So going back to my job application exercise solution if the static methods do not limit the testability of my code is it still bad to use? my validate method was very simple 'Validator.notNull(p,"paramName")' now why would I ever want to mock that?

非常感谢.

推荐答案

不使用TDD的一个明显迹象是协作者使用静态方法和静态类成员.您不能覆盖静态方法,因此不能替代模拟程序来单独使用此类方法测试类.

A tell-tale sign of not using TDD is usage of static methods and static class members for collaborators. You cannot override a static method, so you cannot substitute a mock to test the class using such methods in isolation.

您可以使用依赖项注入来代替在协作器上使用静态协作器或静态方法.在一个简单的编码练习中,您将手动通过构造函数或setter注入依赖项.在现实生活中,您可以使用一种可用的依赖关系框架.

Instead of using static collaborators or static methods on the collaborators, you can use dependency injection. In a simple coding exercise you would inject dependency via a constructor or via the setters by hand. In the real life you can use one of available dependency frameworks.

这篇关于使用TDD方法并避免Java静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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