Constructor method in interface?

I see many say that constructor in interface is bad practice.
But, what about constructor injection?
I mean, suppose that Dispatcher class depends on Router object.
So, the argument of __construct() must be an instance of RouterInterface.

Then, I think about the constructor design contract in the interface.
Hmm… But, I remember that constructor in interface is bad.
Should I just not limit the constructor argument? :confused:

The whole point of coding to an interface is to allow objects to be swapped out for alternative implementations. If you specify the constructor in the interface, you’re preventing alternative implementations that might have different dependencies.

2 Likes

As @fretburner said, the biggest disadvantage of putting a constructor in an interface is that any classes which implement it must all have the same dependencies. By assuming that all subclasses have the same dependencies, the interface is enforcing some assumptions about the implementation of the class. This is the exact opposite of what an interface is for: The interface should only enforce the API of the class, not the specific implementation.

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.