Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Factory functions efficiency

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?

like image 375
Kelvin Zhao Avatar asked Dec 01 '25 10:12

Kelvin Zhao


1 Answers

The advantage is the clarity for the developers that makeSound() is something specific to Dogs.

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.

like image 95
Pac0 Avatar answered Dec 03 '25 22:12

Pac0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!