Hacker News new | ask | show | jobs
by native_samples 1585 days ago
No - that's not what factories are at all.

If you want a simple function to create objects, you have those in OOP languages. They're called constructors. They don't even have names independent of the thing they construct, so they're as lightweight as you can get. And if you do want names, you have static methods or top level named functions (depending on language).

Factories exist for a few different reasons:

1. When there are more things to configure about the newly created objects than makes sense to pass as function properties.

2. When an API designer wishes to provide backwards compatibility to his clients, which adding function parameters doesn't do.

3. When there's a need to separate how something is constructed from where it is constructed, i.e. you create a "factory" or "builder", configure what you want it to do, but then don't directly use it. Instead you pass it off to some other code that uses it when it needs to.

These are fundamental concepts. They aren't some side effect of how OO languages work. I think the disdain for them comes largely from programmers who haven't actually done many different types of programming. If all you've ever done is write web apps then yeah they're sometimes going to seem a bit useless. If you've shipped a type safe library API that you've needed to maintain compatibility for over a period of many years, maybe that will be used in ways you didn't anticipate so you can't just arbitrary refactor yourself out of a hole, suddenly these sorts of abstractions start to look pretty good.

1 comments

point 3 is exactly what I'm saying
But the concept of a factory is independent from whether you name it. In Java you can write a factory like this:

    () -> new Thing(foo, bar);
Behind the scenes it's a class, but you don't write it as such and you don't name it. Nonetheless, it's still a factory.
It's vacuous concept.

Also you're leveraging anonymous function syntax which is, interesting, to say the least. In Java 8- you'd have to write boilerplate class named after a pattern. Lastly creating something from outside information was done since forever, it's trivial when you don't invent ceremony around it. Hence my conclusion, it's a waste of time and effort.

No, because you still need to name the thing the function is assigned to. What exactly should the user of the function call it? thingMakingFunction? You need a consistent way to refer to "a function call that creates an object in a particular state" and factory is as good a word as any.

Yes, in Java 7 or below it'd have required more verbose syntax. So what? That came out 8 years ago and Java isn't the only OO language with a notion of factories. C# had delegates much longer than Java had lambdas, and it also needs a way to talk about "a bit of code that produces objects complying with a contract", so also talks about factories.