Reputation: 2425
I've been seeing examples of factory functions like this,
const dog = () => {
const sound = 'woof'
return {
makeSound: () => console.log( sound )
}
}
const poodle = dog()
poodle.makeSound() // woof
But this way, every dog created will have an extra makeSound function created in memory. Wouldn't it be much better if the functions are external to the object created and just have the object be passed to the sound function like so?
const dog = () => {
return {
sound: 'woof'
}
}
const makeSound = obj => console.log( obj.sound )
const poodle = dog()
makeSound( poodle ) // woof
What's the advantage of having the functions within each object created by the factory function vs having it outside and passing in the object you want to run the function with to it?
Upvotes: 3
Views: 90
Reputation: 23174
The advantage is the clarity for the developers that makeSound()
is something specific to Dog
s.
Imagine you don't know the definition of the function.
The code :
makeSound(arg);
is valid with any argument in javascript. Or none, as it happens (then it will be just considered undefined
).
Nothing prevents a developer from calling
const myUnrelatedObject = { foo: "bar" };
makeSound(myUnrelatedObject); // compiles and returns no error (will just print "undefined")
whereas the "object oriented" way will throw a runtime error
myUnrelatedObject.makeSound(); // TypeError: makeSound is not a function
Code good practices / patterns are made for human developers!
But you're right, there is an overhead. And that is the same for a lot of languages, when it comes to object-oriented patterns.
If this has actually a performance hit on your application, you can and should consider a trade-off between memory and readability (and thus, software maintenance cost).
But as a "default", I'll highly recommend (for you, your colleagues and your company) that you choose the path of the readability and maintainability first.
Also, keep in mind that you should really measure the performance impact in real situations. JavaScript compilers/engine nowadays can be very good at optimizing code, especially if it written in a usual, predictable way.
Upvotes: 1