+ 6

In OO languages, what is the advantage of using factory methods and private constructors to create objects?

What's the advantage over using a public constructor and no factory method?

15th Dec 2019, 11:13 PM
Sonic - avatar
4 Answers
+ 5
When you don't want other users to create an instance of your class or if all methods would be declared as static then private constructor should be used. With factory method, you can create an instance using the "new" keyword
15th Dec 2019, 11:26 PM
Mirielle - avatar
+ 4
Sometimes you have to. Depens on the language! Consider this C++ class: class Foo { const Bar bar; } You ought to initialize `bar` in the constructor initializer and not in the constructor body, because it is const. But maybe `Bar` has no straightforward constructor to use, or you need to do some work before you can create a `Bar` object. Your only option is to pass an already working `Bar` to the constructor of `Foo`: Foo(Bar b) : bar(b) { } That ctor can be private, and a factory method takes care of creating the `Bar` object first. In Javascript (or python, php etc) there is no method overloading and therefor no constructor overloading, which naturally leads to factory methods like class Foo { constructor () {} static fromBar(bar) { ... } static fromQux(qux) { ... } } Another semi-common usecase is the singleton pattern, where a factory method makes sure that there is only one instance of your class. All in all factory methods add extra flexibility I'd say. Edit: Letters
16th Dec 2019, 3:44 AM
Schindlabua - avatar
+ 2
~ swim ~ Sure but that doesn't solve the problem our hypothetical `Bar` class is having.
16th Dec 2019, 8:08 AM
Schindlabua - avatar
+ 2
But if `Bar` doesn't have a proper constructor applicable for the ctor initializer then it's even less applicable while declaring a class. :/
16th Dec 2019, 8:13 AM
Schindlabua - avatar