1

Let's say I have a complex class, perhaps a House so I separate out its creation logic into a factory class, HouseFactory.Build()

However, these classes are for a API DLL, and we've found that many of our consumers are confused and unable to discern that they need to use the HouseFactory, so we add the following static shortcut function to the House class:

class House
{
     public static House Build()
     {
         return houseFactory.Build();
     }
}

What would the potential drawbacks be, of having a creation method in the class that outsources the actual logic to a factory?

1 Answers1

4

Here are some drawbacks:

  • You're creating a circular dependency between HouseFactory and House.
  • Is it using a global? Globals are bad. If not a global, where is houseFactory defined, and who constructs and assigns to it?
  • May not be safe? What happens if House.Build() is called before houseFactory is set? Can houseFactory be changed?
  • It's inflexible. House.Build can only build houses in one specific way, but using HouseFactory directly is bound to be more flexible.
  • It's redundant--which may create more confusion in users. They may not know which is the best method to create instances of House. It also may confuse maintainers. You may have bug fixes incorrectly applied to House.Build() instead of being applied to HouseFactory
  • It may be difficult to unit test. Is it possible mock houseFactory?
  • It will still require documentation for users to read. You will have to explain exactly what kind of house is created by House.Build(). It would be just as easy to document House to state that HouseFactory should be used to construct instances and avoid these drawbacks.

Some alternatives:

  • Document how instances of House should be constructed both on House itself and in your user guides.
  • Depending on your language choice you may be able to restrict access to House' s constructor to your namespace. This will force the user to consult the documentation and use HouseFactory.
Samuel
  • 9,237