Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I've been seeing a lot of code recently that looks like this:

public interface IFoo { int Bar(); }

public static class Foo 
{
    public static IFoo Create() { return new FooImpl(); }
    private class FooImpl : IFoo
    {
        public int Bar () { ... }
    }
}

Basically, there is a contract defined by an interface, the the main business object class is a static class that provides factory methods, and there is an embedded class that provides the actual implementation.

There are some advantages to this pattern especially, the clean separation between the contract and the implementation. Still, it seems a little ugly to me: especially the naming of a static factory class with a business object name rubs me the wrong way.

My questions are...
1. Is there a name for this pattern or style of development?
2. What do you think about this pattern? Are there any other advantages besides a rigorous hiding of implementation? Is there a better way to achieve the same goals?

share|improve this question
add comment

1 Answer

It looks like a crippled cross between Abstract Factory and Factory Method. It includes a full class, not just a method, but that class is a static utility class, not abstract, thus you have no way of switching to a different Foo implementation.

Hiding the implementation of Foo is fine, however this design is not unit testable. Clients most likely call Foo.Create directly, thus unit tests have a hard time replacing / mocking out FooImpl to any different implementation of IFoo.

I agree with you in that the naming is bad too. The factory should not be mixed with the product it creates.

An alternative could of course be a full Abstract Factory implementation, but this may be overkill for a single product. Very often this can be replaced by Dependency Injection, which is simpler and easy to unit test.

share|improve this answer
1  
+1: Like the thoughts about unit tests. –  Loki Astari Sep 27 '11 at 14:39
    
Yep, you're right. This is not unit testable. –  afeygin Sep 27 '11 at 15:02
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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