I've been thinking about having multiple page elements and making tabbing with a PageFactory. Then I realized it would be better to not to type all the types that I want, since I just wanna get the instance.
Then I created something as follows:
public static T GetInstance<T>() where T:IPage, new()
{
return new T();
}
But the point is, I can just create my pages like new WelcomePage(); instead of PageFactory.GetInstance<WelcomePage>() and it doesn't make sense to me to have a generic method like that. But I see it is something used before.
So, what is the benefit of using that generic way to get an instance. I'd be happy to hear, probable needs.
Given that this is static method, I see no benefits over new, except usage of GetInstance in other generic methods. (Non static factory, as a part of interface or abstracts class, and with more that 1 implementation, would get more sense, as client would not depend on specific factory, or e.g. different factory could be used in tests than in production).
I would prefer new, because:
it's immediately understandable, and doesn't require an extra looking into implementation details of GetInstance
given that GetInstance<T> is generic, and constructor constraints on generics are limited to parameterless constructor new (), this implies that dependencies will be injected into T object via properties or ambient environment, neither of which is ideal. Dependency injection via constructor is much better.
Related
I have a class called ReportWorkflow<TReport> that calls some objects to generate a report of a specific type, the object are always called in the same sequence and the only true difference is the actual implementation of each object.
The constructor of this class looks like:
public ReportWorkflow(... , IFileNameProvider<TReport> fileNameProvider)
The ReportWorkflow<TReport> is constructed using dependency injection.
There are multiple ReportWorkflow<TReport> registered at the same time in the DI Container, like:
services.AddSingleton<IReportWorkflow, ReportWorkflow<HrReport>();
services.AddSingleton<IReportWorkflow, ReportWorkflow<AccountingReport>();
//More ReportWorkflows registrations...
To make sure that I get the correct file name provider for every ReportWorkflow<TReport> I've added the generic parameter TReport to the interface IFileNameProvider<TReport> but this interface never uses the generic parameter and it is only there to 'mark' and distinguish an implementation from another.
The interface definition is as follows
public interface IFileNameProvider<TReport> {
string GetFileName();
}
An implementation simply fills the generic parameter with the report type and it will be registered like:
services.AddSingleton<IFileNameProvider<HrReport>, HrFileNameProvider>();
services.AddSingleton<IFileNameProvider<AccountingReport>, AccountingFileNameProvider>();
This will ensure that when I will try to resolve ReportWorkflow<HrReport> I will get HrFileNameProvider and when I will try to resolve ReportWorkflow<AccountingReport> I will get AccountingFileNameProvider.
The 'type markers' HrReport or AccountingReport are actual classes used and returned by other objects and do contain some information.
Does it make sense to have interfaces that use generic parameters just as a sort of 'marker' to distinguish one implementation from another? And if yes, does this pattern have a name?
Congratulations, you may just have reinvented phantom types ;)
While it's a (quaint) thing in Haskell and other statically typed functional programming languages, the question here also implies that it may not be the most idiomatic design to apply to C#.
All that said, it seems to me that this is a workaround to make a DI Container work with the design. When a DI Container is in the way, it'd be worthwhile to consider whether it actually adds value, or if it's rather a liability.
Consider throwing away the container and instead relying on Pure DI. That could make everything simpler, and might also make the use of phantom types redundant.
I found that my design is wrong and asking you how solve my problem.
So my case:
I'm writing factory method, for classes, witch was derived from my special base class. So I wrote
public T MyFactory<T>() where T:MyBaseClass
But my the main work of my factory method is getting some special parameters and passing it to constructor of new object. MyBaseClass has this constructor:
public MyBaseClass(MySpecParam param){...}
But there is no guarantee that type T, derived from MyBaseClass, has such a constructor.
The only solution I see, is to add new() constraint and virtual Init method to MyBaseClass, so that the factory can safely create a new object of type T, and then init it with MySpecParam object.
But, MyBaseClass has such design, so it's completely unusable if it is not inited with MySpecParam. And user can create MyBaseClass with parameterless constructor and get completely invalid, not initialized, object. I think it's not good.
There is no way to add new(MySpecParam) constraint.
How must I design my objects, constructors and factory method?
If each class has only one public constructor, you can find that by reflection, determine what parameters it takes, and supply the appropriate values when you call the constructor (still through reflection).
Otherwise, I presume you have a finite set of constructor signatures. In that case, you'll need some way of determining which constructor to call; the decision may be based in part on the identity of the type argument T.
EDIT
If you're not willing to use reflection for the reasons outlined in your comment, then the answer is more or less "no, you can't do that." Michael Yoon suggests an IoC framework, which of course uses reflection and is subject to run-time errors as well. In my experience (with Castle Windsor), performance has never been a problem, and run-time errors as the result of misconfiguration are caught almost immediately in the development cycle.
Another thought; this may not be helpful, but it might be worth considering. You could use a Func<T> to create the instance, or even have overloads of the factory method for different types of Func<T, TOut>, Func<T1, T2, TOut>, etc, where you call
var obj = FactoryMethod<SomeType>(() => new SomeType(23));
Alternatively, consider the abstract factory pattern.
Sounds like a problem for an IoC container. If your factory used a container like StructureMap or Unity, your constructor issue would no longer be a concern. The factory would ask StructureMap (for example) to resolve MyBaseClass, and it would return an instance your MyBaseClass using the greediest constructor, recursively building all of its dependencies and so forth.
Constructors are not inherited, nor are they allowed on interfaces. This means that each class's constructor are specific only to that class. That also means that a subclass could be made of your base class that doesn't have a constructor that matches your pattern. If you want to have a standard way of configuring your objects, I think an abstract Init(foo, bar, baz), on your base class, similar to your idea, is the best solution. You could also implement internal logic that throws if the objects are accessed before they are initialized, but unfortunately, you won't be able to enforce that at compile time.
I most commonly am tempted to use "bastard injection" in a few cases. When I have a "proper" dependency-injection constructor:
public class ThingMaker {
...
public ThingMaker(IThingSource source){
_source = source;
}
But then, for classes I am intending as public APIs (classes that other development teams will consume), I can never find a better option than to write a default "bastard" constructor with the most-likely needed dependency:
public ThingMaker() : this(new DefaultThingSource()) {}
...
}
The obvious drawback here is that this creates a static dependency on DefaultThingSource; ideally, there would be no such dependency, and the consumer would always inject whatever IThingSource they wanted. However, this is too hard to use; consumers want to new up a ThingMaker and get to work making Things, then months later inject something else when the need arises. This leaves just a few options in my opinion:
Omit the bastard constructor; force the consumer of ThingMaker to understand IThingSource, understand how ThingMaker interacts with IThingSource, find or write a concrete class, and then inject an instance in their constructor call.
Omit the bastard constructor and provide a separate factory, container, or other bootstrapping class/method; somehow make the consumer understand that they don't need to write their own IThingSource; force the consumer of ThingMaker to find and understand the factory or bootstrapper and use it.
Keep the bastard constructor, enabling the consumer to "new up" an object and run with it, and coping with the optional static dependency on DefaultThingSource.
Boy, #3 sure seems attractive. Is there another, better option? #1 or #2 just don't seem worth it.
As far as I understand, this question relates to how to expose a loosely coupled API with some appropriate defaults. In this case, you may have a good Local Default, in which case the dependency can be regarded as optional. One way to deal with optional dependencies is to use Property Injection instead of Constructor Injection - in fact, this is sort of the poster scenario for Property Injection.
However, the real danger of Bastard Injection is when the default is a Foreign Default, because that would mean that the default constructor drags along an undesirable coupling to the assembly implementing the default. As I understand this question, however, the intended default would originate in the same assembly, in which case I don't see any particular danger.
In any case you might also consider a Facade as described in one of my earlier answers: Dependency Inject (DI) "friendly" library
BTW, the terminology used here is based on the pattern language from my book.
My trade-off is a spin on #BrokenGlass:
1) Sole constructor is parameterized constructor
2) Use factory method to create a ThingMaker and pass in that default source.
public class ThingMaker {
public ThingMaker(IThingSource source){
_source = source;
}
public static ThingMaker CreateDefault() {
return new ThingMaker(new DefaultThingSource());
}
}
Obviously this doesn't eliminate your dependency, but it does make it clearer to me that this object has dependencies that a caller can deep dive into if they care to. You can make that factory method even more explicit if you like (CreateThingMakerWithDefaultThingSource) if that helps with understanding. I prefer this to overriding the IThingSource factory method since it continues to favor composition. You can also add a new factory method when the DefaultThingSource is obsoleted and have a clear way to find all the code using the DefaultThingSource and mark it to be upgraded.
You covered the possibilities in your question. Factory class elsewhere for convenience or some convenience within the class itself. The only other unattractive option would be reflection-based, hiding the dependency even further.
One alternative is to have a factory method CreateThingSource() in your ThingMaker class that creates the dependency for you.
For testing or if you do need another type of IThingSource you would then have to create a subclass of ThingMaker and override CreateThingSource() to return the concrete type you want. Obviously this approach only is worth it if you mainly need to be able to inject the dependency in for testing, but for most/all other purposes do not need another IThingSource
I vote for #3. You'll be making your life--and the lives of other developers--easier.
If you have to have a "default" dependency, also known as Poor Man’s Dependency Injection, then you have to initialize and "wire" the dependency somewhere.
I will keep the two constructors but have a factory just for the initialization.
public class ThingMaker
{
private IThingSource _source;
public ThingMaker(IThingSource source)
{
_source = source;
}
public ThingMaker() : this(ThingFactory.Current.CreateThingSource())
{
}
}
Now in the factory create the default instance and allow the method to be overrided:
public class ThingFactory
{
public virtual IThingSource CreateThingSource()
{
return new DefaultThingSource();
}
}
Update:
Why using two constructors:
Two constructors clearly show how the class is intended to be used. The parameter-less constructor states: just create an instance and the class will perform all of it's responsibilities. Now the second constructor states that the class depends of IThingSource and provides a way of using an implementation different than the default one.
Why using a factory:
1- Discipline: Creating new instances shouldn't be part of the responsibilities of this class, a factory class is more appropriate.
2- DRY: Imagine that in the same API other classes also depend on IThingSource and do the same. Override once the factory method returning IThingSource and all the classes in your API automatically start using the new instance.
I don't see a problem in coupling ThingMaker to a default implementation of IThingSource as long as this implementation makes sense to the API as a whole and also you provide ways to override this dependency for testing and extension purposes.
You are unhappy with the OO impurity of this dependency, but you don't really say what trouble it ultimately causes.
Is ThingMaker using DefaultThingSource in any way that does not conform to IThingSource? No.
Could there come a time where you would be forced to retire the parameterless constructor? Since you are able to provide a default implementation at this time, unlikely.
I think the biggest problem here is the choice of name, not whether to use the technique.
The examples usually related to this style of injection are often extremely simplisitic: "in the default constructor for class B, call an overloaded constructor with new A() and be on your way!"
The reality is that dependencies are often extremely complex to construct. For example, what if B needs a non-class dependency like a database connection or application setting? You then tie class B to the System.Configuration namespace, increasing its complexity and coupling while lowering its coherence, all to encode details which could simply be externalized by omitting the default constructor.
This style of injection communicates to the reader that you have recognized the benefits of decoupled design but are unwilling to commit to it. We all know that when someone sees that juicy, easy, low-friction default constructor, they are going to call it no matter how rigid it makes their program from that point on. They can't understand the structure of their program without reading the source code for that default constructor, which isn't an option when you just distribute the assemblies. You can document the conventions of connection string name and app settings key, but at that point the code doesn't stand on its own and you put the onus on the developer to hunt down the right incantation.
Optimizing code so those who write it can get by without understanding what they are saying is a siren song, an anti-pattern that ultimately leads to more time lost in unraveling the magic than time saved in initial effort. Either decouple or don't; keeping a foot in each pattern diminishes the focus of both.
For what it is worth, all the standard code I've seen in Java does it like this:
public class ThingMaker {
private IThingSource iThingSource;
public ThingMaker() {
iThingSource = createIThingSource();
}
public virtual IThingSource createIThingSource() {
return new DefaultThingSource();
}
}
Anybody who doesn't want a DefaultThingSource object can override createIThingSource. (If possible, the call to createIThingSource would be somewhere other than the constructor.) C# does not encourage overriding like Java does, and it might not be as obvious as it would be in Java that the users can and perhaps should provide their own IThingSource implementation. (Nor as obvious how to provide it.) My guess is that #3 is the way to go, but I thought I would mention this.
Just an idea - perhaps a bit more elegant but sadly doesn't get rid of the dependency:
remove the "bastard constructor"
in the standard constructor you make the source param default to null
then you check for source being null and if this is the case you assign it "new DefaultThingSource()" otherweise whatever the consumer injects
Have an internal factory (internal to your library) that maps the DefaultThingSource to IThingSource, which is called from the default constructor.
This allows you to "new up" the ThingMaker class without parameters or any knowledge of IThingSource and without a direct dependency on DefaultThingSource.
For truly public APIs, I generally handle this using a two-part approach:
Create a helper within the API to allow an API consumer to register "default" interface implementations from the API with their IoC container of choice.
If it is desirable to allow the API consumer to use the API without their own IoC container, host an optional container within the API that is populated the same "default" implementations.
The really tricky part here is deciding when to activate the container #2, and the best choice approach will depend heavily on your intended API consumers.
I support option #1, with one extension: make DefaultThingSource a public class. Your wording above implies that DefaultThingSource will be hidden from public consumers of the API, but as I understand your situation there's no reason not to expose the default. Furthermore, you can easily document the fact that outside of special circumstances, a new DefaultThingSource() can always be passed to the ThingMaker.
I know interfaces cannot define constructors. Here's what I wish I could do:
public interface SavableObject {
void Save(ObjectSaver saver);
SavableObject(ObjectLoader loader); //This, obviously, doesn't work
}
//Loading an object inside ObjectLoader:
T LoadObject<T>() where T : SavableObject {
return (T)Activator.CreateInstance(typeof(T), this);
}
And I could do this if I took out the line that didn't work, and there would just be a runtime error when trying to load (or possibly save, if I put an assert in there) the object if it didn't have the constructor. I'm just wondering if there's any way to require a class to have a particular constructor that can be used with the Activator. Can I use a custom attribute somehow, and require that attribute to be on the class? Or must I rely on runtime checks to load and save data?
I know I could have a parameterless constructor and a Load(ObjectLoader) method but I don't necessarily want to have a parameterless constructor available to abuse for other purposes.
what about ISerializable?
In brief I suggest you use generics as most factories do.
public interface SavableObject<T> : where T : new
{
void Save(IObjectSaver<T> saver);
SavableObject<T> Load(ObjectLoader loader); //This, obviously, doesn't work
}
However, you seem to have turned it on it head. The class is doing what factory must do. So I do not think it is such a good idea to pass the factory to the entity itself and that is part of the problem you are experiencing in the design.
If you are not afraid of using Reflection, like Activator that you have shown, you can do little trick I tend to use:
Make parameterless constructor that is protected
Make Load method, that is also protected (or private, I tend to use virtual protected so I support inheritance)
Create new object using this non-public constructor (through reflection - you can't create instance of your class "just like that" using new operator)
Invoke load method (also using reflection - no one will call it later).
I don't know if this will work for you, but I used that method when I needed to deserialize pretty big game state and it was pretty fast, eventhough all this reflection (for many reasons I did not wanted to use built-in serialization methods and Factory Pattern wouldn't do, so I tend to treat this method as something that may be useful if other methods fail, on the other hand, if I could - I would probably use built-in serialization for simplicity).
How about adding a property on your interface:
public interface SavableObject
{
void Save(ObjectSaver saver);
ObjectLoader ObjectLoader {get; set;}
}
Then in your factory:
T LoadObject<T>() where T : SavableObject
{
var result = (T)Activator.CreateInstance(typeof(T));
result.ObjectLoader = this;
return result;
}
Based on your question and comments.
I think you should do it at runtime using reflection.
Combining constructors and interfaces is ilogical from its core. Interface is about what concrete instance can do, not how to initialize it. This can only be achived using abstract class.
Maybe using factory to create instance of the class?
Also I don't think you can get better speed than default ISerializable implementation. Unless you are .NET GURU and have years of time for it.
Short answer: It's not possible, I guess. There are no attributes or generalizations I can use to require a specific kind of constructor on a class.
I like the idea of "programming to interfaces" and avoiding the use of the "new" keyword.
However, what do I do when I have two classes that have the same interface but are fundamentally different to set up. Without going into detail about my specific code, I have an interface with a method, "DoStuff". Two classes implement this interface. One is very simple and requires no initialisation to speak of. The other has five different variables that need to be set up. When combined, they allow for literally millions of ways for the class to work when DoStuff is called.
So when do I "new" these classes? I though about using factories but I don't think they are suitable in this case because of the vast difference in setup. (BTW: there are actually about ten different classes using the interface, each allowing the formation of part of a complex pipeline and each with different configuration requirements).
I think you may be misunderstanding the concept of programming to interfaces. You always have to use the new keyword in object oriented languages to create new instances of objects. Just because you program to interfaces doesn't remove that requirement.
Programming to an interface simply means that all your concrete classes have their behavior defined in an interface instead of in the concrete class itself. So when you define the type of a variable, you define it to be the interface instead of a concrete type.
In your case, just implement DoStuff in your concrete classes as each class needs it implemented (whether doing it simply or with 10 other initialized objects and setup). For example, if you have an interface IInterface and class SomeClass which implements IInterface. You might declare an instance of SomeClass as such:
IInterface myInstance = new SomeClass();
This allows you to pass this instance around to other functions without having to have those functions worry about the implementation details of that instance's class.
Well you really have 3 options. Use new, use a factory or use an DI container. With a DI container your five variables would most likely need to be in a configuration file of some sorts.
But to be completely honest it sounds like you're making your life harder than it needs to be by forcing yourself into a corner. Instead of coding to some ideal, rather code in a manner which best facilitates solving the problem at hand. Not saying you should do a hack job of it, but really, saying you don't want to use new, that is really making your life harder than it needs to be...
Regardless of what you use, at some point you're going to have to construct instances of your classes in order to use them, there's no way around that.
How to go about doing that depends on what you want to accomplish, and the semantics of those classes.
Take the class you mention with those fields.
Can those fields be read from somewhere? A configuration file, as an example? If so, perhaps all you need is just a default constructor that initializes those fields from such a configuration file.
However, if the content of those fields really needs to be passed in from the outside world, there's no way around that.
Perhaps you should look at a IoC container and Dependency Injection?
If you are passing that many configuration parameters into your class it may have too many responsibilities. You should look into breaking it up into smaller classes that only have a single responsibility.
Avoiding the new keyword can be valuable because it creates a dependancy on the implementing class. A better solution would be to use Dependancy Injection.
for example
public interface IDoStuff
{
void DoStuff();
}
public class DoStuffService
{
private IDoStuff doer;
public DoStuffService()
{
//Class is now dependant on DoLotsOfStuff
doer = new DoLotsOfStuff(1,true, "config string");
}
}
public class DoStuffBetterService
{
private IDoStuff doer;
//inject dependancy - no longer dependant on DoLotsOfStuff
public DoStuffBetterService(IDoStuff doer)
{
this.doer = doer;
}
}
Obviously you still have to create the IDoStuff object being passed in somewhere.
An Inversion of Control (IoC) container is a good tool to help with implementing this.
Here is a good tutorial for Castle Windsor Container if you are interested in learning more. (There are many other IoC containers, I just happen to use this one.)
The example in your question was very abstract, so I hope this answer is helpful.
If I understand you correctly the problem is with different initialization. You need to provide for two classes that have the same interface. One does not need anything, and the other needs some paramaters and calls some complex initialization.
You should use have a constructor that gets InitializationParameter. Both classes should get it. One with a simple interface that does not need to get anything from it. The other that needs params and will get them from it.
If you are concerned about initialization you can use factory, just ask it for some interface providing this init parameter and factory will create, init and return to you the object according to the values you provided.
If something is not clear - please ask.