6

I am having some problems trying to figure out when to use a factory or to wrapper class. This question is slightly geared towards C# I guess, so I'm not sure if this is the correct place to ask.

Say there is a library that exposes an interface called IStackExchangeClient, and multiple differing implementations of that interface (private implementations that clients will not know about), HttpStackExchangeClient, UdpStackExchangeClient.

We can allow the object creation of the interface through a factory, like StackExchangeClientFactory.Create(), or we can wrap it up in another class like StackExchangeClient that internally does the same thing, but simply proxies.

In the second instance, clients can write new StackExchangeClient() which feels much more natural to me. So my question is, when do I choose one or the other? What are some of the considerations that I should be taking in?

I've thought hard about it and I can't choose between one style or the other, but clearly some parts of the .NET framework use factories, and some parts don't, even when there are multiple underlying implementations of its interface.

Thank you!

  • 2
    "we can wrap it up in another class like StackExchangeClient that internally does the same thing, but simply proxies" - can you give some more details, maybe an example how the design shall look like for this case? – Doc Brown Dec 27 '14 at 12:31
  • Factories are discouraged in the .net framework design guidelines, from what I remember. – Frank Hileman Dec 29 '14 at 1:34
  • 1
    @FrankHileman: See this MSDN article; it describes two common uses of factory patterns in the .NET Framework. One of them is Type Conversion, the other is returning an appropriate concrete class (conforming to a specific interface), based on a condition. – Robert Harvey Dec 29 '14 at 6:08
  • A third choice would be to have a private constructor for StackExchangeClient and a static method StackExchangeClient.Create that returns an initialized instance of an object. That would be a "factory" method as opposed to a separate factory class. Also note that while you are using the term factory, you are probably actually doing something more like the "Builder" pattern. My rule of thumb is if the initialization is especially complex I'll use a builder, otherwise I'll just use the standard constructor. – Mike Dec 29 '14 at 13:42
  • 2
    @RobertHarvey Here are the .net framework design guidelines for constructors. Microsoft's usability research for API design indicated that factory based constructors are harder to discover (not really surprising). – Frank Hileman Dec 30 '14 at 15:19
1

If you're using dependency injection then using the Factory Pattern hides the dependencies of the object you're creating from the consumer. For instance:

class MyClass
{
    MyClass(IDependencyA dependencyA, IDependencyB dependency) { ... }
}

If you want to create this directly, you do:

var myClass = new MyClass(dependencyA, dependencyB);

That means your consuming class has to take dependencies on all the dependencies of what you're creating. If MyClass has lots of dependencies, and is created lots of places, then having a MyClassFactory provides decoupling:

class MyClassConsumer
{
    private readonly IMyClassFactory factory;

    MyClassConsumer(IMyClassFactory factory)
    {
        this.factory = factory;
    }

    ...

    private void someMethod()
    {
        var myClass = this.factory.Create();
    }
}

As you can see, MyClassConsumer is now totally decoupled from the dependencies of MyClass. If the dependencies of MyClass change, you now only have to change the Factory implementation, and nothing else changes.

Consider this: any class that calls new is by definition a factory. Trying to follow the Single Responsibility Principle means creating an object should be the responsibility of a Factory class, and it should be that class's only responsibility.

  • Why not introduce IMyclass interface and inject it into MyClassConsumer? – Sher10ck May 25 '15 at 17:24
  • @Sher10ck - That wouldn't produce the same functionality, and reduces the flexibility. If you inject an instance, it implies a Singleton. The consumer needs to be able to create instances of MyClass on demand, so it needs to be injected with a factory, not a single instance. It's the factory's job to determine how to create it (possibly a singleton instance, or sometimes a single instance per thread, or one instance per call, and it can provide the parameters for instantiation that the calling method doesn't care about). – Scott Whitlock May 26 '15 at 15:35
1
 > Object creation: when should I expose a factory vs wrapping class?

Answer from unit-testing point of view:

If you want to do unit-testing and the test requires you to change the object-creation of child-items the factory (method or class) is the way to go.

If your program is scattered with several IOrderItem orderItem = new OrderItem(...) you cannot replace OrderItem with a fake.

If your progam uses the factory method IOrderItem orderItem = createOrderItem(..) it is easy to replace OrderItem with a fake by reimplementing/mocking the factory method.

The only pro wrapping-class argument i can think of is that it is more intuitive and easier to discover for the api-consumer as stated in @Frank Hileman s comment.

0

Use a wrapping class when the interface is private, i.e. the user can't create their own new derived classes. This is usually a pretty questionable design.

Otherwise, make the interface and derived classes public.

Don't use a factory method unless it has some language-required advantage, e.g. generic type deduction, which you can see in Tuple.Create.

  • I don't think it's always wise to make the derived classes public. If you're writing a library (as he is), the consumer has no business knowing which particular implementation of an interface is being used or even could possibly be used. All they need to know is that they have an IStackExchangeClient, which should act like any other IStackExchangeClient. – mgw854 Dec 26 '14 at 17:11
  • This answer appears to say both "don't use a wrapper class" and "don't use a factory method", so I'm confused as to what you think he should do. – Ixrec Jan 25 '15 at 12:40
0

A Factory allows for the creation of objects that require complex setup code, or shared setup code across implementations. You should not perform the same complex setup in a constructor as a constructor is only intended to initialize an object and get it ready for use by setting member variables.

The StackExchangeClientFactory.Create() implementation allows you to perform setup-code that is shared across implementations, determine the most appropriate implementation for use and then return that implementation. In the wrapper you would have to perform the same setup-code in your constructor, which should be avoided.

Also, if you are using DI (Dependency Injection), which you should, you would use a Factory to return the appropriate implementation to the DI framework. The Create-method on the Factory applies logic to determine the appropriate implementation and returns that.

0

I do not quite understand your question. And I think there are some misconceptions:

I) A factory is a design pattern used to separate object creation from object consumption. There are two possible ways to deal with that:

1) You delegate instance creation to a separate object

2) A static method is used to create instances

The advantage: Dependencies are no longer created. The object in need asks for its dependencies. Factories allow dependency injection. But instead of managing a dozen factories and all the wiring up, you leave that for an abstraction called (DI-) container.

II) An Interface is the C#/Java way of dealing with multiple inheritance. Instead of letting object inherit implementations from multiple objects, you only inherit an API so to say. An interface is a contract that defines an API and leaves the implementation to the object. Objects define families of somehow related objects via an is-a-relationship, you could say, interfaces define a relationship of different objects sharing common behaviour.

What does that mean for (I)?

If you have a factory for different objects who follow the same API, the return-type of the factory is the common interface ( think of ILogging with FileLogger, DatabaseLogger, EventlogLogger and so on).

The consuming object only gets something that behaves like a Logger. It doesn't need to know which kind of logger it is using - even if it is a NullLogger.

III) A Proxy could be any object mimicing another object. A common usecase is mock objects. You wrap one functionality with another.

Which one you want to implement depends on your intention:

  • If you are designing an object which needs somehow to use a common API for HttpStackExchangeClient and UdpStackExchangeClient you would imlement it via IStackExchangeClient and a factory

  • Say HttpStackExchangeClient and UdpStackExchangeClient have a different API and you want one behave like the other you would use a proxy wrapping up the other.

  • If you have IStackExchangeClient as an interface and HttpStackExchangeClient and UdpStackExchangeClient implement it as well, using a proxy makes no sense, since the consuming object does not know which one it is going to use.

I've thought hard about it and I can't choose between one style or the other, but clearly some parts of the .NET framework use factories, and some parts don't, even when there are multiple underlying implementations of its interface.

Note, that the framework has a history and was not always designed thoroughly (I would bet), which might be the reason for some inconsistencies.

0

Just use the simple constructor.

In this particular case factory is a more obscure API for no reason.

Add the factory when it's clearly needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.