How would you know when to use factory functions?

Question

How would you know when to use factory functions?

Answer

Since Factory Functions are meant to create alike objects in a way that makes it easier to produce in mass quantities, a possible example when you would think on using a factory function instead of making a regular object literal would be a social network where let’s say each profile is an object, if we wanted a very minimalistic user with only name, image, friends and posts we could dynamically create them with a factory function where we could also have methods to add friends and create posts:

const makeUser = (id, name, image) => {
  return({
    id,
    name,
    image,
    friends: [],
    posts: [],
    addFriend (friend) {
       this.friends.push(friend);
    },
    createPost (post) {
      this.posts.push(post);
    }
  })
}

Now every time a user wants to sign up in our very simple social network app when they click sign up, this function will be triggered and they will become a new user object, where if they decide to add a friend the .addFriend() method will trigger with the friend to be added to the friends array.

34 Likes

2 posts were split to a new topic: How is the key & value decided for the properties

2 posts were split to a new topic: How do u assign new friends/post values

2 posts were split to a new topic: What is the difference between Factory Functions and Classes?

HI i have got two questions here
1>>>>It still works even without passing any arguments in robotFactory function. why ???

return{
model : model,
mobile : mobile
}
why its same name of key value in object ???

const robotFactory = (model, mobile) => {

return{

model: model,

mobile: mobile,

beep(){

  console.log('Beep Boop');

}

}

}; const tinCan = robotFactory();

tinCan.beep();

3 Likes

Because those are the names given to the parameters. If we change the names of the parameters then we would assign those names…

const robotFactory = (a, b) => {
  return{
    model: a,
    mobile: b,
    beep(){
      console.log('Beep Boop');
    }
  }
}

Keep in mind that even though we don’t see the quotes, the keys are strings.

13 Likes

so it means property’s key or value name must be same as parameter to assign the right value to the right property of the object . If i am right if it makes sense??

1 Like

Correct. We are the authors so the order is what we make it.

7 Likes

const robotFactory = (model,mobile) =>{

return{

model: model,

mobile: mobile,

beep() {

console.log('Beep Boop')

}

}

};

const tinCan = robotFactory(‘P-500’,true)

console.log(tinCan.beep())

//when i run this why i got this output

//Beep Boop
//undefined

//Beep Boop is okay but why i got undefined?

4 Likes

You don’t need to console.log() the tinCan.beep() since the method already runs a console.log() in it’s declared expression.

In essence your console is runing: console.log(console.log(tinCan.beep())) which is why you get two results.

7 Likes

Let’s say you have to create multiple instances of an object in which you have the same properties, but each object has different corresponding values, so if you write a factory function, than besides writing multiple objects, you can invoke a factory function in which the arguments you write will be your values, and set it equal to a variable which would be your new object.
For Example:
const personFactory = (firstName, lastName, age) => {
return {
firstName,
lastName,
age
}
}

const alexander = personFactory(Alexander, Hamilton, 40);
const thomas = personFactory(Thomas, Jefferson, 45);

console.log(alexander);
// equals
alexander = {
firstName: Alexander,
lastName: Hamilton,
age: 40
}

console.log(thomas);
// equals
thomas = {
firstName: Thomas,
lastName: Jefferson,
age: 45
}

3 Likes

Note that when console logging a console.log(), the outer console.log() will simply log the returned value of the inner console.log(). The reason it logs undefined to the console is because console.log() actually retuns undefined

2 Likes

Why don’t we just use a class or a constructor?

1 Like

A function factory created module is disposable and can be used in an higher-order function with a smaller footprint on memory, and no footprint in the global namespace.

3 Likes

good info. thanks :slight_smile:

1 Like

I was wondering, I saw you didn’t assign the keys the value held in the parameters. What will happen when we call that factory function and we do pass arguments? The keys would not get anything assigned to them, am I correct to assume this?

Okay just tested it for myself. How!!?? lol. Even though it doesn’t directly assign the parameter value to the key it still assigns it and to the correct key! Is it because the parameter has the same name as the key? Does it just know?

1 Like

That is an ES6 technique called, destructuring. The keys will be assigned the arguments given to the function as given by their parameter name, so, yes to your question.

Like electronics, it’s wired that way in the background. It only knows what we tell it, but also is wired in such a way as to match parameters to key names, and assign corresponding values. Keep you eye on the arguments sent to the factory. Those are the values represented by the parameters and given to the keys.


Edit: map parameters

3 Likes

Factory functions that only return objects have a very small footprint. The constructor approach of creating objects undoubtedly has a larger overhead and footprint, but that would need to be confirmed. Something else I know very little about is the leakage that can result from either. Maybe none, but that will need to be researched when the question matters. This is by far the simpler way to produce objects of the same makeup, and no methods attached.

That last statement warns of a drawback to factory functions that contain methods. Every object produced by the factory will carry the extra code base, so will add to overhead cumulatively. If however they are used as transient objects then their memory is released, or garbage collected. It is in this process where leakage will eventually become evident, if there is any. Testing would be tricky, but the engineers know how to do this with millions of iterations until memory runs out, which, if there is leakage, will happen on a typical PC.

This is really none of our concern, at present, so long as we know it will eventually be part of our responsibility when designing and writing production code. By then we will have the supports around us to help carry the load, so don’t make it one, just now or anytime in the near future. Toss efficiency and write code that works. That’s the goal today.

5 Likes

This social network would only be built with simple html, css and javascript? or can this be applied for example to react or nextjs?

Can I ask a stupid question…trying to add one more method to the Robot factory function with an intention so that can also be accessed the same way as beep() Can I know if that is doable? Or I’m doing something seriously silly?

const robotFactory = (model, mobile, mileage) => {
return {
model : model,
mobile : mobile,

beep() {
console.log('Beep Boop')

}

mileage(){
console.log(‘mileage’)
}

}

}

const tinCup = robotFactory(‘P600’, true, ‘Castrol’)
tinCup.mileage()