'When to pass a parameter as a constructor parameter or as a method parameter
I currently have this class that uses a Service class in a class method. Currently I am creating an instance of the service class in my method as shown below. The question I am wondering is that when it comes to testing, I am using spock and it seems to be difficult to test when a new instance of a class is being created in the method rather than being passed in as a constructor parameter for dependency injection. I am wondering would passing in an instance of Service class into Handler as a constructor parameter be the correct way of doing this? Thanks
public class Handler{
private Service service;
public Handler(){}
public void someMethod(ObjectNeededForService object){
service = new Service(object);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
