简体   繁体   English

Java样式/最佳实践 - 将字段传递给方法直接访问

[英]Java Style / Best Practice - passing fields to methods vs accessing directly

In Java, given the following class: 在Java中,给出以下类:

public class MyClass {
   private final Dependency dependency;
   public MyClass(Dependency dependency)
   {
       this.dependency = dependency;
   }

   public void doWork()
   {
       // validate dependency...
   }

The doWork method needs to invoke a method that uses dependency . doWork方法需要调用使用dependency的方法。

Which of the following two variations is considered "best practice", and why? 以下哪两种变体被认为是“最佳实践”,为什么?

   // Access dependency directly
   void validateDependency()
   {
        this.dependency.something();
   }

   // access dependency as passed to the method
   void validateDependency(Dependency dependency)
   {
       dependency.something();
   }

I find myself favouring the latter, passing the dependency directly to the method, as it makes the method easier to test in isolation (albeit, marginally). 我发现自己偏爱后者,将依赖项直接传递给方法,因为它使得该方法更容易单独测试(虽然是边缘)。

However, I'm interested in the java convention / best practice here. 但是,我对这里的java约定/最佳实践很感兴趣。

A class exists because you have state and operations that are coupled to that state. 存在一个类,因为您具有与该状态耦合的状态和操作。 There's no good reason to pass part of that state as a parameter to a class method. 将该状态的一部分作为参数传递给类方法是没有充分理由的。

In fact, it would indicate to me that that piece of state should not actually belong to the class. 事实上,它会向我表明,这片国家不应该属于这个阶级。 Or that the method doesn't belong to the class. 或者该方法不属于该类。

Using a parameter "so that it's easier to unit test" is a good indication that the latter holds (the method should not be in the class). 使用参数“以便更容易进行单元测试”是后者保持的一个很好的指示(该方法不应该在类中)。

Well, in your example you are asking the function to do something with Dependency which lends itself to a static function, not a member function. 好吧,在你的例子中,你要求函数用Dependency做一些事情,它适用于静态函数,而不是成员函数。

My rule of thumb is: Use members directly when calling a method on an object that owns the member but pass references when doing/testing something directly related to the dependency and favor static methods for the latter 我的经验法则是: 在拥有成员的对象上调用方法时直接使用成员,但在执行/测试与依赖项直接相关的内容时传递引用,并为后者支持静态方法

That a bit verbose but I hope it helps. 有点冗长,但我希望它有所帮助。 As always try to "do the right thing" and differences this small won't likely make a huge impact on maintenance or readability of your code. 一如既往地尝试“做正确的事情”和差异,这个小的不会对代码的维护或可读性产生巨大影响。

There isnt a right way to do it. 没有正确的方法来做到这一点。 I prefer just putting the variable there. 我更喜欢把变量放在那里。

Dependency injection. 依赖注入。 The second option is "best". 第二种选择是“最好的”。

If you make your "Dependency" class an interface it makes code more modular, easier to test, less coupled. 如果将“Dependency”类设置为接口,则会使代码更加模块化,更易于测试,更少耦合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM