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.
Java is always Pass by Value and not pass by reference, we can prove it with a simple example. Let's say we have a class Balloon like below. And we have a simple program with a generic method to swap two objects, the class looks like below.
What is Actually Passed to a Method? The data that is passed to a method is used inside the method to accomplish tasks. Definition clarification: What is passed "to" a method is referred to as an "argument". The "type" of data that a method can receive is referred to as a "parameter".
You can add as many parameters as you want, just separate them with a comma.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With