开发者

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

In Java, given the following class:

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.

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.


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.

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜