Home > Enterprise >  When to pass a parameter as a constructor parameter or as a method parameter
When to pass a parameter as a constructor parameter or as a method parameter

Time:03-01

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);
}
}

CodePudding user response:

This is a tricky question and you'll find different answers for that. If I understand correctly, you are basically asking if constructor injection is better than setter injection or vice versa, correct?

Obviously constructor injection is neat when you have a limited amount of fields in your class. Constructors with 20 args are not very readable and should definitely be avoided. In that case you would have to use setter injection and call the setters for the individual fields one by one.

But maybe if you have a class with so many fields that need injecting, it would be good to refactor and get your dependencies down to a smaller amount.

Personally I prefer construtor injection but there are arguments against it.

  • Related