Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

interfaces and constructors in delphi

I'm writing a framework for business objects.. I'm heavily using interfaces because of:

1) Automatic memory management
2) Separation of concerns

Usually constructors have a few parameters that are objects of the framework, but I can't put them in the interfaces.

My question is, if I'm using interfaces to make a separation of concern of the classes that implements them, why my code ends up binded still to the concrete class that implements the interface to call the constructor and its parameters.. and

What's the merit of putting the creator code in a factory method? (something I'm still not using..)

Thanks!

=== EDIT ===

The point in my question are the constructor's paremeters.. In the framework lots of objects needs a few other to work.. The answers adress well the point of separation of concerns, but still I don't see how the solve the problem of parameters..

If I don't go the constructor way, I should go the "procedure Initialize" way (in the interface) and "CheckObjectInitialized" (protected) in every method of the object.. how this will be cleaner?

like image 958
pragmatic_programmer Avatar asked Nov 03 '11 03:11

pragmatic_programmer


1 Answers

If you are feeling the need to add constructors to your interfaces, you are doing something wrong.

Interfaces are simply a declaration of functionality. How that functionality gets provided is of no concern to the interface. Indeed, how the implementing objects are created should be of absolutely no concern to the consumer of an interface. This is where Dependency Injection comes in.

Dependency Injection is the notion that the implementation of your interfaces is completely decoupled from the code actually using the interface. It is more than a factory class (as deftly describe by Marjan) in that it allow you to completely decouple the declaration and implementation of an implementing class from the interface.

Thus, when you declare an interface, a Dependency Injection container can create/fetch an instance of the implemented object automatically, removing the need for you to even create it. In this way, your application becomes merely a wiring together of interfaces without any concern for construction of anything. Your library code is revealed only through the DI container.

The Delphi Spring Framework provides a very nice DI Container for you to use. You can find the Delphi Spring Framework and the Spring Container here:

http://code.google.com/p/delphi-spring-framework/

like image 52
Nick Hodges Avatar answered Sep 17 '22 12:09

Nick Hodges