mercredi 18 octobre 2017

Correct way of passing instance argument

Suppose I manage pizzera and I want to know when the first order of the day arrive.

I have two classes: Orders (storing orders) and Events. I am invoking a function getCurrentEvents() which checks if the order is the first order of the day.

Q: When should I pass the Orders argument to getCurrentEvents()? Moreover, could you give me a hint how's this topic called so I can read more about similiar design problems?

1st method

pass Orders while creating Events instance, use it directly in function

class Pizzeria {
  constructor() {
    this.orders = new Orders()
    // pass Orders here
    this.events = new Events(this.orders)
  }

  getCurrentEvents() {
    this.events.getCurrentEvents();
  }
}

class Events {
  constructor(orders) {
    this.orders = orders;
  }

  getCurrentEvents() {
    this.firstOderOfTheDay();
  }

  firstOrderOfTheDay() {
    ...do something with this.orders
  }
}

2nd method

again pass Orders while creating Events instance but pass it to the function

class Pizzeria {
  constructor() {
    this.orders = new Orders()
    this.events = new Events(this.orders)
  }

  getCurrentEvents() {
    this.events.getCurrentEvents();
  }
}

class Events {
  constructor(orders) {
    this.orders = orders;
  }

  getCurrentEvents() {
    // pass Orders here
    this.firstOderOfTheDay(this.orders);
  }

  firstOrderOfTheDay({ orders }) {
    ...do something with passed orders
  }
}

3rd method

pass it after Events instance is created

class Pizzeria {
  constructor() {
    this.orders = new Orders()
    this.events = new Events()
  }

  getCurrentEvents() {
    // pass Orders here
    this.events.getCurrentEvents(this.orders);
  }
}

class Events {
  getCurrentEvents(orders) {
    this.firstOderOfTheDay(orders);
  }

  firstOrderOfTheDay({ orders }) {
    ...do something with orders
  }
}

Aucun commentaire:

Enregistrer un commentaire