All the hoopla around composition and factory functions

I’m reading about and experimenting with JS prototypes. I keep running into sermons on factory functions over constructors and composition over inheritance.

Does it just come down to finding more ways to use functions instead of class hierarchies? Is being able to abstract problems in terms of composition of any utility to beginners?

Pretty much that’s what they’re advocating. Basically when OOP first came out people tried to solve everything with inheritance. Fast forward about 20 years and now we know that if you bring code in using inheritance then you’re creating a brittle coding situation and not saving you much work. It’s better to use inheritance sparingly and to compose your code with a focus more on data.

Now, the only problem I see with your post is people advocating using “factories”. Can you point me at where you’re reading that? Because to me “factory” is actually a symptom of using too much inheritance, and in a language like JavaScript you just don’t need them.

This is the particular article regarding factory functions that got me to post the question last night. It’s still OOP, but the author describes it as more of a “has-a/can-do” vs “is-a” way of using classes. I had read another article and a couple of YouTube videos on the topic of composition as well.

1 Like

Wow! That’s fun and informative. Thanks for sharing @austen

Ah, I see. So in this they’re using the word “Factory” to mean a function that crafts old-school style prototype objects. In the new ES6 style classes you don’t need those, and in the articles you reference he talks about why they’re better. I’d say the one thing he doesn’t get into is that the new ES6 classes are consistent. In the old style people did all kinds of crazy hacks and workarounds that made a lot of their code incompatible with other people’s code. It’d work for just using it, but if you tried to extend it you’d run into some weirdo hack they did to make some obscure OOP thing work.

The new ES6 classes are consistent, and that means everyone can use them to extend what you’ve implemented. That’s kind of the whole point of OOP in the first place. There’s no benefit to just wrapping functions and data up into some randomly designed prototype if nobody can then extend your design for their own code. The new ES6 classes make that much easier.