Erik Lenaerts

Do, or do not. There is no try. - Yoda

Initialization using Interfaces

Hi,

For some time now, I'm a dedicated user of Interfaces in my code. I really like to develop using Interfaces because it offers a loosely coupled integration between my components.

However, I find them having one minor drawback, that is, they don't support initialization as constructors do for classes. When I define an interface and want all objects that implement this interface to have an initial state, then I typically add an Initialize method on this interface.  

interface IWork
{
    void Initialize(string jobName);
}

Having an Initialize method is not that hard to understand for a developer that implement this Interface. Secondly a developer always has to implement all members, so you can be sure a class always has a "certain" implementation. 

The problem is more at the client side (client as in code that uses the class), a constructor can be something that is enforced by the class upon its clients. But this is not something you can enforce when working with interfaces. Of course the class could have a constructor on its own, but then this is not regulated by the Interface.

Secondly the Initialize method has - as ex VB developer - a rather unfortunate connotation. In VB we didn't had even constructors, so we had to rely on an Initialize method. However, back then we had to write code to check if the Initialize method was called and if it was forgotten, we had to throw an exceptions (erh, "raising" an error)

Since an Interface defines all operations a class must implement, I would find it logically that we similarly could define its constructors. This way, having a specific interface could enforce the implementation of a certain constructor. This statement however imposes one problem, constructors share the same name as its class, so that's pretty difficult for an Interface to do. Theoretically, we could use the Interface name for this purpose like:

interface IWork
{
    IWork(string jobName);
}

Unfortunately this is only theory, but it would make a small difference, at least for me.

Posted: May 22 2006, 10:02 AM by ErikL | with no comments
Filed under: ,
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: