Are constructor methods in interfaces bad?
Whether or not they are bad, I am not aware of any language that has the ability to specify a constructor on an interface.
That being said, however, I personally do not believe that the constructor of an object is part of that object's interface and as such adding a constructor to an interface would inhibit the natural flexibility that interfaces afford.
They are bad in that they serve no purpose. At its core, an interface is simply a data passing contract. There is no implemenation attached with an interface and hence there is nothing to initialize and no need for a constructor.
If you need some sort of initialization your much better off using an abstract class.
Although interfaces can't have constructors in most languages, the Factory pattern provides a contract for constructing objects, similar to an interface. Take a look at that.
What if your object implemented more than one interface? In what order should 'interface constructors' be called?
Why do people think that anybody wants to instantiate the interface?
What we want to do is to force implementers to implement the constructor, just like other interface methods.
An interface is like a contract. Let's say I have an interface Queue, and I want to make sure that implementers create a constructor with one argument, which creates a singleton queue (A new queue with just that element). Why should that not be part of the contract? With at least Java interfaces, that cannot be specified.
First off, I disagree that interface is just a data passing contract. If that were true you would be allowed to define properties in an interface.
I wouldn't exactly think it's weird to do something like:
interface IDBConnection
{
function __construct( $connectionString );
function executeNonQuery( $commandText, $paramters=null);
function executeScalar( $commandText, $paramters=null);
function executeSingle( $commandText, $paramters=null);
function executeArray( $commandText, $paramters=null);
}
This would enable you to create instances of third party classes for data access based on simple reflection instead of just being a data contract.
I'm pretty sure that this isn't the best example, I'd go for an abstract base class here in the real world, but I'm also pretty sure that there are perfectly valid reasons for defining a constructor methods' contract in an interface that I haven't thought of.
I haven't seen it done, but i wouldn't think it to be weird or bad.