How many constructors should a class have? - class-design

I'm currently modifying a class that has 9 different constructors. Now overall I believe this class is very poorly designed... so I'm wondering if it is poor design for a class to have so many constructors.
A problem has arisen because I recently added two constructors to this class in an attempt to refactor and redesign a class (SomeManager in the code below) so that it is unit testable and doesn't rely on every one of its methods being static. However, because the other constructors were conveniently hidden out of view about a hundred lines below the start of the class I didn't spot them when I added my constructors.
What is happening now is that code that calls these other constructors depends on the SomeManager class to already be instantiated because it used to be static....the result is a null reference exception.
So my question is how do I fix this issue? By trying to reduce the number of constructors? By making all the existing constructors take an ISomeManager parameter?
Surely a class doesn't need 9 constructors! ...oh and to top it off there are 6000 lines of code in this file!
Here's a censored representation of the constructors I'm talking about above:
public MyManager()
: this(new SomeManager()){} //this one I added
public MyManager(ISomeManager someManager) //this one I added
{
this.someManager = someManager;
}
public MyManager(int id)
: this(GetSomeClass(id)) {}
public MyManager(SomeClass someClass)
: this(someClass, DateTime.Now){}
public MyManager(SomeClass someClass, DateTime someDate)
{
if (someClass != null)
myHelper = new MyHelper(someOtherClass, someDate, "some param");
}
public MyManager(SomeOtherClass someOtherClass)
: this(someOtherClass, DateTime.Now){}
public MyManager(SomeOtherClass someOtherClass, DateTime someDate)
{
myHelper = new MyHelper(someOtherClass, someDate, "some param");
}
public MyManager(YetAnotherClass yetAnotherClass)
: this(yetAnotherClass, DateTime.Now){}
public MyManager(YetAnotherClass yetAnotherClass, DateTime someDate)
{
myHelper = new MyHelper(yetAnotherClass, someDate, "some param");
}
Update:
Thanks everyone for your responses...they have been excellent!
Just thought I'd give an update on what I've ended up doing.
In order to address the null reference exception issue I've modified the additional constructors to take an ISomeManager.
At the moment my hands are tied when it comes to being allowed to refactor this particular class so I'll be flagging it as one on my todo list of classes to redesign when I have some spare time. At the moment I'm just glad I've been able to refactor the SomeManager class...it was just as huge and horrible as this MyManager class.
When I get around to redesigning MyManager I'll be looking for a way to extract the functionality into two or three different classes...or however many it takes to ensure SRP is followed.
Ultimately, I haven't come to the conclusion that there is a maximum number of constructors for any given class but I believe that in this particular instance I can create two or three classes each with two or three constructors each..

A class should do one thing and one thing only. If it has so many constructors it seems to be a tell tale sign that it's doing too many things.
Using multiple constructors to force the correct creation of instances of the object in a variety of circumstances but 9 seems like a lot. I would suspect there is an interface in there and a couple of implementations of the interface that could be dragged out. Each of those would likely have from one to a few constructors each relevant to their specialism.

As little as possible,
As many as necessary.

9 constructors and 6000 lines in class is a sign of code smell. You should re-factor that class.
If the class is having lot of responsibilities and then you should separate them out. If the responsibilities are similar but little deviation then you should look to implement inheritance buy creating a interface and different implementations.

If you arbitrarily limit the number of constructors in a class, you could end up with a constructor that has a massive number of arguments. I would take a class with 100 constructors over a constructor with 100 arguments everyday. When you have a lot of constructors, you can choose to ignore most of them, but you can't ignore method arguments.
Think of the set of constructors in a class as a mathematical function mapping M sets (where each set is a single constructor's argument list) to N instances of the given class. Now say, class Bar can take a Foo in one of its constructors, and class Foo takes a Baz as a constructor argument as we show here:
Foo --> Bar
Baz --> Foo
We have the option of adding another constructor to Bar such that:
Foo --> Bar
Baz --> Bar
Baz --> Foo
This can be convenient for users of the Bar class, but since we already have a path from Baz to Bar (through Foo), we don't need that additional constructor. Hence, this is where the judgement call resides.
But if we suddenly add a new class called Qux and we find ourselves in need to create an instance of Bar from it: we have to add a constructor somewhere. So it could either be:
Foo --> Bar
Baz --> Bar
Qux --> Bar
Baz --> Foo
OR:
Foo --> Bar
Baz --> Bar
Baz --> Foo
Qux --> Foo
The later would have a more even distribution of constructors between the classes but whether it is a better solution depends largely on the way in which they are going to be used.

The answer: 1 (with regards to injectables).
Here's a brilliant article on the topic: Dependency Injection anti-pattern: multiple constructors
Summarized, your class's constructor should be for injecting dependencies and your class should be open about its dependencies. A dependency is something your class needs. Not something it wants, or something it would like, but can do without. It's something it needs.
So having optional constructor parameters, or overloaded constructors, makes no sense to me. Your sole public constructor should define your class's set of dependencies. It's the contract your class is offering, that says "If you give me an IDigitalCamera, an ISomethingWorthPhotographing and an IBananaForScale, I'll give you the best damn IPhotographWithScale you can imagine. But if you skimp on any of those things, you're on your own".
Here's an article, by Mark Seemann, that goes into some of the finer reasons for having a canonical constructor: State Your Dependency Intent

It's not just this class you have to worry about re-factoring. It's all the other classes as well. And this is probably just one thread in the tangled skein that is your code base.
You have my sympathy... I'm in the same boat.
Boss wants everything unit tested, doesn't want to rewrite code so we can unit test. End up doing some ugly hacks to make it work.
You're going to have to re-write everything that is using the static class to no longer use it, and probably pass it around a lot more... or you can wrap it in a static proxy that accessses a singleton. That way you an at least mock the singleton out, and test that way.

Your problem isn't the number of constructors. Having 9 constructors is more than usual, but I don't think it is necessarily wrong. It's certainly not the source of your problem. The real problem is that the initial design was all static methods. This is really a special case of the classes being too tightly coupled. The now-failing classes are bound to the idea that the functions are static. There isn't much you can do about that from the class in question. If you want to make this class non-static, you'll have to undo all that coupling that was written into the code by others. Modify the class to be non-static and then update all of the callers to instantiate a class first (or get one from a singleton). One way to find all of the callers is to make the functions private and let the compiler tell you.
At 6000 lines, the class is not very cohesive. It's probably trying to do too much. In a perfect world you would refactor the class (and those calling it) into several smaller classes.

Enough to do its task, but remember the Single Responsibility Principle, which states that a class should only have a single responsibility. With that in mind there are probably very few cases where it makes sense to have 9 constructors.

I limit my class to only have one real constructor. I define the real constructor as the one that has a body. I then have other constructors that just delegate to the real one depending on their parameters. Basically, I'm chaining my constructors.
Looking at your class, there are four constructors that has a body:
public MyManager(ISomeManager someManager) //this one I added
{
this.someManager = someManager;
}
public MyManager(SomeClass someClass, DateTime someDate)
{
if (someClass != null)
myHelper = new MyHelper(someOtherClass, someDate, "some param");
}
public MyManager(SomeOtherClass someOtherClass, DateTime someDate)
{
myHelper = new MyHelper(someOtherClass, someDate, "some param");
}
public MyManager(YetAnotherClass yetAnotherClass, DateTime someDate)
{
myHelper = new MyHelper(yetAnotherClass, someDate, "some param");
}
The first one is the one that you've added. The second one is similar to the last two but there is a conditional. The last two constructors are very similar, except for the type of parameter.
I would try to find a way to create just one real constructor, making either the 3rd constructor delegate to the 4th or the other way around. I'm not really sure if the first constructor can even fit in as it is doing something quite different than the old constructors.
If you are interested in this approach, try to find a copy of the Refactoring to Patterns book and then go to the Chain Constructors page.

Surely a class should have as many constructors as are required by the class... this doesnt mean than bad design can take over.
Class design should be that a constructor creates a valid object after is has finished. If you can do that with 1 param or 10 params then so be it!

It seems to me that this class is used to do way, way to much. I think you really should refactor the class and split it into several more specialized classes. Then you can get rid of all these constructors and have a cleaner, more flexible, more maintainable and more readable code.
This was not at direct answer to your question, but i do believe that if it is necessary for a class to have more than 3-4 constructors its a sign that it probably should be refactored into several classes.
Regards.

The only "legit" case I can see from you code is if half of them are using an obsolete type that you are working to remove from the code. When I work like this I frequently have double sets of constructors, where half of them are marked #Deprecated or #Obsolete. But your code seems to be way beyond that stage....

I generally have one, which may have some default parameters. The constructor will only do the minimum setup of the object so it's valid by the time it's been created. If I need more, I'll create static factory methods. Kind of like this:
class Example {
public:
static FromName(String newname) {
Example* result = new Example();
result.name_ = newname;
return result;
}
static NewStarter() { return new Example(); }
private:
Example();
}
Okay that's not actually a very good example, I'll see if I can think of a better one and edit it in.

The awnser is: NONE
Look at the Language Dylan. Its has a other System.
Instat of a constructors you add more values to your slots (members) then in other language. You can add a "init-keyword". Then if you make a instance you can set the slot to the value you want.
Ofcourse you can set 'required-init-keyword:' and there are more options you can use.
It works and it is easy. I dont miss the old system. Writing constructors (and destructors).
(btw. its still a very fast language)

I think that a class that has more than one constructor has more than one responsibility. Would be nice to be convinced about the opposite however.

A constructor should have only those arguments which are mandatory for creating the instance of that class. All other instance variables should have corresponding getter and setter methods. This will make your code flexible if you plan to add new instance variables in the future.
In fact following OO principle of -
For each class design aim for low coupling and high cohesion
Classes should be open for extension but closed for modification.
you should have a design like -
import static org.apache.commons.lang3.Validate.*;
public class Employee
{
private String name;
private Employee() {}
public String getName()
{
return name;
}
public static class EmployeeBuilder
{
private final Employee employee;
public EmployeeBuilder()
{
employee = new Employee();
}
public EmployeeBuilder setName(String name)
{
employee.name = name;
return this;
}
public Employee build()
{
validateFields();
return employee;
}
private void validateFields()
{
notNull(employee.name, "Employee Name cannot be Empty");
}
}
}

Related

Excluding member functions and inheritance, what are some of the most common programming patterns for adding functionality to a class?

There're likely no more than 2-4 widely used approaches to this problem.
I have a situation in which there's a common class I use all over the place, and (on occasion) I'd like to give it special abilities. For arguments sake, let's say that type checking is not a requirement.
What are some means of giving functionality to a class without it being simply inheritance or member functions?
One way I've seen is the "decorator" pattern in which a sort of mutator wraps around the class, modifies it a bit, and spits out a version of it with more functions.
Another one I've read about but never used is for gaming. It has something to do with entities and power-ups/augments. I'm not sure about the specifics, but I think they have a list of them.
???
I don't need specific code of a specific language so much as a general gist and some keywords. I can implement from there.
So as far as I understand, you're looking to extend an interface to allow client-specific implementations that may require additional functionality, and you want to do so in a way that doesn't clutter up the base class.
As you mentioned, for simple systems, the standard way is to use the Adaptor pattern: subclass the "special abilities", then call that particular subclass when you need it. This is definitely the best choice if the extent of the special abilities you'll need to add is known and reasonably small, i.e. you generally only use the base class, but for three-to-five places where additional functionality is needed.
But I can see why you'd want some other possible options, because rarely do we know upfront the full extent of the additional functionality that will be required of the subclasses (i.e. when implementing a Connection API or a Component Class, each of which could be extended almost without bound). Depending on how complex the client-specific implementations are, how much additional functionality is needed and how much it varies between the implementations, this could be solved in a variety of ways:
Decorator Pattern as you mentioned (useful in the case where the special entities are only ever expanding the pre-existing methods of the base class, without adding brand new ones)
class MyClass{};
DecoratedClass = decorate(MyClass);
A combined AbstractFactory/Adaptor builder for the subclasses (useful for cases where there are groupings of functionality in the subclasses that may differ in their implementations)
interface Button {
void paint();
}
interface GUIFactory {
Button createButton();
}
class WinFactory implements GUIFactory {
public Button createButton() {
return new WinButton();
}
}
class OSXFactory implements GUIFactory {
public Button createButton() {
return new OSXButton();
}
}
class WinButton implements Button {
public void paint() {
System.out.println("I'm a WinButton");
}
}
class OSXButton implements Button {
public void paint() {
System.out.println("I'm an OSXButton");
}
}
class Application {
public Application(GUIFactory factory) {
Button button = factory.createButton();
button.paint();
}
}
public class ApplicationRunner {
public static void main(String[] args) {
new Application(createOsSpecificFactory());
}
public static GUIFactory createOsSpecificFactory() {
int sys = readFromConfigFile("OS_TYPE");
if (sys == 0) return new WinFactory();
else return new OSXFactory();
}
}
The Strategy pattern could also work, depending on the use case. But that would be a heavier lift with the preexisting base class that you don't want to change, and depending on if it is a strategy that is changing between those subclasses. The Visitor Pattern could also fit, but would have the same problem and involve a major change to the architecture around the base class.
class MyClass{
public sort() { Globals.getSortStrategy()() }
};
Finally, if the "special abilities" needed are enough (or could eventually be enough) to justify a whole new interface, this may be a good time for the use of the Extension Objects Pattern. Though it does make your clients or subclasses far more complex, as they have to manage a lot more: checking that the specific extension object and it's required methods exist, etc.
class MyClass{
public addExtension(addMe) {
addMe.initialize(this);
}
public getExtension(getMe);
};
(new MyClass()).getExtension("wooper").doWoop();
With all that being said, keep it as simple as possible, sometimes you just have to write the specific subclasses or a few adaptors and you're done, especially with a preexisting class in use in many other places. You also have to ask how much you want to leave the class open for further extension. It might be worthwhile to keep the tech debt low with an abstract factory, so less changes need to be made when you add more functionality down the road. Or maybe what you really want is to lock the class down to prevent further extension, for the sake of understand-ability and simplicity. You have to examine your use case, future plans, and existing architecture to decide on the path forward. More than likely, there are lots of right answers and only a couple very wrong ones, so weigh the options, pick one that feels right, then implement and push code.
As far as I've gotten, adding functions to a class is a bit of a no-op. There are ways, but it seems to always get ugly because the class is meant to be itself and nothing else ever.
What has been more approachable is to add references to functions to an object or map.

Is it ok to put methods/fields to base class that will only be used by some of the derived classes

This is a bit of a generic software design question. Suppose you have a base class and lots of classes that derive from it (around 10).
There is some common functionality that is being shared between some of the classes (3-4 of derived classes need it). Basically a field for a UI control, an abstract method to create a UI control and the common code that uses the abstract method to recycle the UI piece (8-9 lines of code) using the abstract method. Something like this:
class BaseClass {
...
protected UIControl control;
protected abstract UIControl CreateUI();
protected void RecycleUI() {
if (/* some condition is met */) {
if (this.control != null) {
control.Dispose();
}
this.control = this.CreateUI();
this.AddToUITree(control);
}
}
...
}
Do you think it is OK to put this to base class instead of replicating the code in derived classes.
Drawback is that this piece of code is only used for some of the base classes and completely irrelevant for the other classes.
One alternative is to create an intermediate class that derives from BaseClass and use it as the base to the ones that need the functionality. I felt like creating a derived class for a couple line of code for a very specific purpose felt heavy. It doesn't feel like it is worth interrupting the inheritance tree for this. We try to keep the hierarchy as simple as possible so that it is easy to follow and understand the inheritance tree. Maybe if this was C++ where multiple inheritance is an option, it wouldn't be a big issue but multiple inheritance is not available.
Another option is to create a utility method and an interface to create/update the UI control:
interface UIContainer {
UIControl CreateUIControl();
UIControl GetUIControl();
void SetUIControl(UIControl control);
}
class UIControlUtil {
public void RecycleUI(UIContainer container) {
if (/* some condition is met */) {
if (container.GetUIControl() != null) {
container.GetUIControl().Dispose();
}
UIControl control = container.CreateUI();
container.SetUIControl(control);
container.AddToUITree(control);
}
}
}
I don't like this option because it bleeds UI logic externally which is less secure as its UI state can be manipulated externally. Also derived classes have to implement getter/setter now. One advantage is that there is another class outside of the aforementioned inheritance tree and it needs this functionality and it can use this utility function as well.
Do you have any other suggestions? Should I just suppress the urges that brew inside me to have common code not repeated?
One alternative is to create an intermediate class that derives from
BaseClass and use it as the base to the ones that need the
functionality.
Well, this is what I thought is the most appropriate. But it depends. The main question here is the following: are objects, that require UI recycling and really different from those, that do not? If they are really different, you have to create a new base class for them. If difference is really negligible, I think it's ok to leave things in a base class.
Do not forget about LSP.
We try to keep the hierarchy as simple as possible so that it is easy
to follow and understand the inheritance tree
I think more important here is to keep things not only simple, but also close to your real world things so that modeling new entities would be easy. Seeming easiness now may cause real troubles in the future.

When are object interfaces useful in PHP? [duplicate]

This question already has answers here:
What is the point of interfaces in PHP?
(15 answers)
Closed 8 years ago.
From php.net:
Object interfaces allow you to create code which specifies which methods
a class must implement, without having to define how these methods are handled.
Why should I need to do that? Could it be a kind of 'documentation'?
When I'm thinking about a class I have to implement, I know exactly which methods I should code.
What are some situations where interfacing a class is a "best practice"?
Short answer: uniform interfaces and polymorphism.
Longer answer: you can obviously just create a class that does everything and indeed you'd know what methods to write. The problem you have with using just concrete classes, however, is your lack of ability to change. Say you have a class that stores your users into a MySQL database, let's call it a UserRepository. Imagine the following code:
<?php
class UserRepositoryMysql {
public function save( User $user ) {
// save the user.
}
}
class Client {
public function __construct( UserRepositoryMysql $repos ) {
$this->repos = $repos;
}
public function save( User $user ) {
$this->repos->save( $user );
}
}
Now, this is all good, as it would actually work, and save the User to the database. But imagine your application will become populair, and soon, there is a question to support PostgreSQL as well. You'll have to write a UserRepositoryPostgresql class, and pass that along instead of UserRepositoryMysql. Now, you've typehinted on UserRepositoryMysql, plus you're not certain both repositories use the same methods. As an aside, there is little documentation for a potential new developer on how to implement his own storage.
When you rewrite the Client class to be dependent upon an interface, instead of a concrete class, you'll have an option to "swap them out". This is why interfaces are useful, obviously, when applied correctly.
First off, my php object coding is way behind my .net coding, however, the principles are the same. the advantages of using interfaces in your classes are many fold. Take for example the case where you need to return data from a search routine. this search routine may have to work across many different classes with completely different data structures. In 'normal' coding, this would be a nightmare trying to marry up the variety of different return values.
By implementing interfaces, you add a responsibility to the clsses that use them to produce a uniform set of data, no matter how disparate they may be. Another example would be the case where you are pulling data from different 'providers' (for example xml, json, csv etc, etc). By implementing an interface on each class type, you open up the possibilities to extend your data feeds painlessly by adding new classes that implement the interface, rather than having a mash-up of switch statements attempting to figure out what your intentions are.
In a word, think of an interface as being a 'contract' that the class 'must' honour. lnowing that means that you can code with confidence for that given scenario with only the implementation detail varying.
Hope this helps.
[edit] - see this example on SO for a fairly simple explanation:
An interface is a concept in Object Oriented programming that enables polymorphism. Basically an interface is like a contract, that by which classes that implement it agree to provide certain functionality so that they can be used the same way other classes that use the interface
purpose of interface in classes
The first case that comes to my mind is when you have a class that uses certain methods of another class. You don't care how this second class works, but expects it to have particular methods.
Example:
interface IB {
public function foo();
}
class B implements IB {
public function foo() {
echo "foo";
}
}
class A {
private $b;
public function __construct( IB $b ) {
$this->b = $b;
}
public function bar() {
$this->b->foo();
}
}
$a = new A( new B() );
$a->bar(); // echos foo
Now you can easily use different object passed to the instance of class A:
class C implements IB {
public function foo() {
echo "baz";
}
}
$a = new A( new C() );
$a->bar(); // echos baz
Please notice that the same bar method is called.
You can achieve similar results using inheritance, but as PHP does not support multiple inheritance, interfaces are better - class can implement more than one interface.
You can review one of PHP design patterns - Strategy.
Say you're creating a database abstraction layer. You provide one DAL object that provides generic methods for interfacing with a database and adapter classes that translate these methods into specific commands for specific databases. These adapters themselves need to have a generic interface, so the DAL object can talk to them in a standardized way.
You can specify the interface the adapters need to have using an Interface. Of course you can simply write some documentation that specifies what methods an adapter needs to have, but writing it in code enables PHP to enforce this interface for you. It enables PHP to throw helpful error messages before a single line of code is executed. Otherwise missing methods could only be found during runtime and only if you actually try to call them, which makes debugging a lot harder and code much more unreliable.

What is the point declaring variables at the end of class?

I saw multiple examples in MSDN that uses to declare the internal fields at the end of the class. What is the point?
I find this a little embarrassing, because each time Visual Studio adds a method it adds it to the end of the class, so there is need every time to move it...
class A
{
public A(){}
// Methods, Properties, etc ...
private string name;
}
class A
{
private string name;
public A(){}
// Methods, Properties, etc ...
}
In C++, it makes sense to put the public interface of the class at the top, so that any user of the class can open up your header file and quickly see what's available. By implication, protected and private members are put at the bottom.
In C# and Java, where interface and implementation are completely intertwined, people would probably not open your class's source code to see what's available. Instead they would rely on code completion or generated documentation. In that case, the ordering of the class members is irrelevant.
If it's obvious the variable has been declared, and the code is by way of an example, then arguably this gets you to the bit being demonstrated quicker - that's all I can think of.
Add-ins like ReSharper will allow you to standardise and automatically apply this layout at the touch of a key combination, by the way, if it is what you want.
Many programmers strive for self-documenting code that helps clients to understand it. In C++ class declaration, they would go from most important (i.e. what is probably most frequently inspected) to least important:
class Class {
public:
// First what interest all clients.
static Class FromFoobar(float foobar); // Named constructors in client code
// often document best
Class(); // "Unnamed" constructors.
/* public methods */
protected:
// This is only of interest to those who specialize
// your class.
private:
// Of interest to your class.
};
Building on that, if you use Qt, the following ordering might be interesting:
class SomeQtClass : public QObject {
public:
signals: // what clients can couple on
public slots: // what clients can couple to
protected:
protected slots:
};
Then the same down for protected and private slots. There is no specific reason why I prefer signals over slots; maybe because signals are always public, but I guess the ordering of them would depend on the situation, anyhow, I keep it consistent.
Another bit I like is to use the access-specifiers to visually seperate behaviour from data (following the importance ordering, behaviour first, data last, because behaviour is the top-interest for the class implementor):
class Class {
private:
void foobar() ;
private:
float frob_;
int glob_;
};
Keeping the last rule helps to prevent visual scattering of class components (we all know how some legacy classes look like over time, when variables and functions are mixed up, not?).
I don't think there is any valid reason for this. If you run Code Analysis on a class declared like this you'll get an error as private fields should be declared on top of classes (and below constants).

generic type dependency injection: How to inject T

I want to handle different types of docs the same way in my application
Therefore:
I have a generic interface like this.
public interface IDocHandler<T>where T: class
{
T Document { get;set;}
void Load(T doc);
void Load(string PathToDoc);
void Execute();
void Execute(T doc);
}
And for different types of documents I implement this interface.
for example:
public class FinanceDocumentProcessor:IDocumentHandler<ReportDocument>
{}
public class MarketingDocumentProcessor:IDocumentHandler<MediaDocument>
{}
Then I can do of course something like this:
IDocumentHandler<ReportDocument> docProc= new FinanceDocumentProcessor();
It would be interessting to know how I could inject T at runtime to make the line above loosly coupled...
IDocumentHandler<ReportDocument> docProc = container.resolve("FinanceDocumentProcessor());
but I want to decide per Configuration wether I want to have my FinanceDomcumentProcessor or my MarketingDocumentProcessor... therefore I would have to inject T on the left site, too ...
Since I have to use c# 2.0 I can not use the magic word "var" which would help a lot in this case... but how can I design this to be open and flexible...
Sorry for the misunderstanding and thanks for all the comments but I have another example for my challenge (maybe I am using the wrong design for that) ...
But I give it a try: Same situation but different Explanation
Example Image I have:
ReportingService, Crystal, ListAndLabel
Three different Reporting Document types. I have a generic Handler IReportHandler<T> (would be the same as above) this Handler provides all the functionality for handling a report Document.
for Example
ChrystalReportHandler:IReportHandler<CrystalReportDocument>
Now I want to use a Framework like Unity (or some else framework) for dependency injection to decide via configuration whether I want to use Crystal, Reportingservices or List and Label.
When I specify my mapping I can inject my ChrystalReportHandler but how can I inject T on the left side or in better word The Type of ReportDocument.
IReportHandler<T (this needs also to be injected)> = IOContainer.Resolve(MyMappedType here)
my Problem is the left Site of course because it is coupled to the type but I have my mapping ... would it be possible to generate a object based on Mapping and assign the mapped type ? or basically inject T on the left side, too?
Or is this approach not suitable for this situation.
I think that with your current design, you are creating a "dependency" between IDocumentHandler and a specific Document (ReportDocument or MediaDocument) and so if you want to use IDocumentHandler<ReportDocument or MediaDocument> directly in your code you must assume that your container will give you just that. The container shouldn't be responsible for resolving the document type in this case.
Would you consider changing your design like this?
public interface IDocumentHandler
{
IDocument Document { get; set; }
void Load(IDocument doc);
void Load(string PathToDoc);
void Execute();
void Execute(IDocument doc);
}
public class IDocument { }
public class ReportDocument : IDocument { }
public class MediaDocument : IDocument { }
public class FinanceDocumentProcessor : IDocumentHandler { }
public class MarketingDocumentProcessor : IDocumentHandler { }
If I understand you correctly, you have two options.
if you have interface IDocHandler and multiple classes implementing it, you have to register each type explicitly, like this:
container.AddComponent>(typeof(FooHandler));
if you have one class DocHandler you can register with component using open generic type
container.AddComponent(typeof(IDocHandler<>), typeof(DocHandler<>));
then each time you resolve IDocHandler you will get an instance of DocHandler and when you resolve IDocHandler you'll get DocHandler
hope that helps
You need to use a non-generic interface on the left side.
Try:
public interface IDocumentHandler { }
public interface IDocumentHandler<T> : IDocumentHandler { }
This will create two interfaces. Put everything common, non-T-specific into the base interface, and everything else in the generic one.
Since the code that you want to resolve an object into, that you don't know the type of processor for, you couldn't call any of the T-specific code there anyway, so you wouldn't lose anything by using the non-generic interface.
Edit: I notice my answer has been downvoted. It would be nice if people downvoting things would leave a comment why they did so. I don't care about the reputation point, that's just minor noise at this point, but if there is something seriously wrong with the answer, then I'd like to know so that I can either delete the answer (if it's way off target) or correct it.
Now in this case I suspect that either the original questionee has downvoted it, and thus either haven't posted enough information, so that he's actually asking about something other than what he's asked about, or he didn't quite understand my answer, which is understandable since it was a bit short, or that someone who didn't understand it downvoted it, again for the same reason.
Now, to elaborate.
You can't inject anything "on the left side". That's not possible. That code have to compile, be correct, and be 100% "there" at compile-time. You can't say "we'll tell you what T is at runtime" for that part. It just isn't possible.
So the only thing you're left with is to remove the T altogether. Make the code that uses the dependency not depend on T, at all. Or, at the very least, use reflection to discover what T is and do things based on that knowledge.
That's all you can do. You can't make the code on the left side change itself depending on what you return from a method on the right side.
It isn't possible.
Hence my answer.