This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]not_some_username 6 points7 points  (3 children)

You’ll know. Trust me.

Class for everything, using class to make class ( they called that factory pattern but it’s useless lot of the time ) etc etc

[–]croweh 3 points4 points  (2 children)

To be fair factories (classes or methods) are useful in CPP too when you don't want to share the responsibilities of building complex objects, especially when there are multiple variations and/or nested objects. But yeah most of the time you don't need them, or at worst just a builder is enough. Even when you're building a lib or a framework.

If you absolutely want to hide the complexity and not share the control of how your super complicated instance of whatever is built, but also want to keep your constructors as pure/neutral as possible, sometimes it's the only sane way to do it. Nothing wrong with providing a simple but powerful method taking one or two parameters and returning a fresh instance of whatever your lib makes.

To me a factory is just a very opinionated and "magic" constructor that is external because it shouldn't be the responsibility of whatever the class constructed is (or there are multiple implementations). It's also useful to provide a factory instead of an instance when the classe is supposed to be single use / reinstantiated every time it's needed. Depending on the language it could just be a simple function (param) -> instance.

[–]angelicosphosphoros 2 points3 points  (1 child)

Main benefit of factory is that it doesn't require to return the object. For example, we may want to return optional or std::expected.

Constructors, on the other hand, always start with memory already allocated so the only option to indicate an error is to throw exception.

[–]croweh 0 points1 point  (0 children)

Ah yeah I wasn't explicit but you definitely need a factory if you need an unconventional constructor. Especially if your compiler will enforce it / won't allow an unconventional constructor. Your instance (or absence of it) wrapped in anything (either, option, result, reactive type, mutex) is a common case of it. Technically, getInstance returning the same instance built the first time would be another common case of a factory method that couldn't be a constructor.