Hello! I am wondering if classes make the ‘factory functions’ we learned during the objects lesson obsolete? Is there a time where it is more appropriate to use a factory function? Or should we generally always use classes to build multiple objects?
Obsolete, no. Special purpose, yes.
I came across this article which you may find interesting.
Classes and factory functions each have their own pros and cons, so it’s up to you to decide which to use in a given situation. The writer of the linked article is firmly in favor of factory functions over classes. I, myself, remain undecided.
What we should do is keep an open mind. Consider what the long term goal is, then decide which is most expedient and simple to justify.
Personally, a class makes sense when we are working with a lot of objects with the same general makeup, same properties, shared methods, inheritable, &c. A factory makes sense when we want a special function with a variable constant that is passed to the factory and constant in the returned function. These returned functions are disposable when we’re done working with them.
Would it be possible to combine both factory functions and classes? say we need a lot of instances of a few classes, could both be used to accomplish this? Or are factory functions specific to object creation?
The objects from factory functions are more transient than those that are class instances. In one-off situations, the more transient form leaves less of a foot print on memory. Classes are better suited to session variables that remain in state for the entire run of the program.
Mind, this is still conjecture, so do a little more research before drawing any conclusions.
Edited 3/29/2022 by mtf: remin => remain
I went through the whole article.
It exhaustively arguments why classes are not a good idea and a lot of devs brush that under the rug (or don’t understand the code maintenance that they require, well enough);
The conclusion would be to use Factories over Classes.
The author also wrote O’Reilly books (the ones used in University classes and comes with a lot of accolades)