1

Should a factory function be in it's own class as a static member or in a namespace? Is there any difference between the two meaning I must use one when creating a class factory?

In my case, the classes produced by the factory are container objects with different memory structures backing them. Something like

template< typename T >
class Parent
{
    virtual void myFunction() = 0;
    // more virtual interface functions...
}

template< typename T >
class ChildA : public Parent< T >
{
    virtual void myFunction() override;
}

template< typename T >
class ChildB : public Parent< T >
{
    virtual void myFunction() override;
}


template< typename T >
Parent< T >* factory( PerformanceTraits traits );

I took a look at Namespace + functions versus static methods on a class and have also read what Scott Meyers has to say on this subject but I don't seem to be able to apply this to factory functions.

If I use a namespace I can write

Parent* obj = MyFactoryNamespace::factory< int >( traits );

compared to

Parent* obj = MyFactoryClass< int >::factory( traits );

if I use a templated factory class. Other than this being two ways to write the same thing are there technical differences?

Thanks.

Community
  • 1
  • 1
user2746401
  • 3,157
  • 2
  • 21
  • 46
  • I think the question you linked already answers this pretty well. The one thing to keep in mind is testing: it is much harder reopen a class than a namespace. – Benjamin Bannier Oct 16 '14 at 12:43

2 Answers2

0

Either way you just get a global with a goofy name. But most readers of the code would expect it to be a static member of the thing it creates, namely Parent. That would be a familiar pattern to me, but using some other namespace seems irrelevant and strange.

Adrian May
  • 2,127
  • 15
  • 24
0

It depends. There's no real answer. In a lot of cases, the only class visible to the user is an abstract base class; the actual class being built by the factory is declared and defined in an unnamed namespace in the source file. In such cases, obviously, the factory functions will be in a namespace, declared in the header. If this pattern is used in your application, then it makes sense to be consistent, and declare all of your factory functions at namespace scope. Otherwise, it's more a question of style. Do whichever feels best to you. (But be consistent.)

James Kanze
  • 150,581
  • 18
  • 184
  • 329