1

What the drawbacks when they pick the constructor with the less parameters first?

Best regards.

Jack Hu
  • 1,315
  • 2
  • 13
  • 27
  • 2
    By picking the greediest constructor, the framework tries to make things easier for you, but it is actually a [bad idea to have types with multiple constructors](http://www.cuttingedge.it/blogs/steven/pivot/entry.php?id=97). – Steven Sep 25 '13 at 07:24
  • If you were an IoC container whose primary purpose was to inject dependencies into constructors, wouldn't you be greedy, too? :) – Facio Ratio Oct 17 '13 at 16:50

1 Answers1

1

The injector tries to guess which constructor to invoke depending on argument type information (that is not always available), the list of constructors in the class (including inherited constructors) and the available parameters that it could supply. In some frameworks, the arguments are explicitly provided and the injector does not need to resolve a constructor but it is not always the case.

I have written some simple constructor dependency injection code. When more than a single constructor is a valid candidate for dependency injection, it's pretty much like regular expression matching : the longest string is assumed to be more specific and therefore used first.

As a matter of fact, the injector assumes that the constructor with more arguments "wraps" the one with less arguments :

MyClass(A,B){
   // does something with A and B
}

MyClass(A,B,C){
   // should call the previous one
   this(A,B);
   //then does something with C
}

This applies to any type of method (not only constructors).

ibtarek
  • 795
  • 4
  • 16