Disclaimer: I am going to write in Python and in the context of web development with Django, but this question is not language nor framework specific.
Let's say I have a
PizzaManager class that serves as a utils tool to select pizzas in a
Restaurant menu. The pizza manager uses data the
restaurant has to perform its different actions:
pizza_manager = PizzaManager(restaurant)
PizzaManager acts as a filter on a specified list of pizzas. The manager deals with different lists of pizzas at a time in different scenarios. So the same pizza manager may be working with
all_pizzas at a certain stage and with
pepperoni_pizzas at another stage. Since the source pizzas is a changing variable, we decided to pass it in via method chaining, rather than using a traditional setter:
pizza_manager.with_pizzas(all_pizzas) pizza_manager.with_pizzas(pepperoni_pizzas) pizza_manager.with_pizzas(pizzas_of_the_year)
with_pizzas method works as follow:
def with_pizzas(self, pizzas): self.pizzas = pizzas return self
As I mentioned, the main job of the manager is to apply filters to the passed in pizzas. For example, let's say we define a
cheap_pizzas method that selects the cheap pizzas from the
def cheap_pizzas(): self.filtered_pizzas = [pizza for pizza in self.pizzas if pizza.price <= self.threshold_price] return self all_pizzas = restaurant.pizza_set.all() pizza_manager.with_pizzas(all_pizzas ).cheap_pizzas()
We can keep filtering by chaining another method:
Finally, to retrieve the list of filtered pizzas we just run the
def get(self): return self.pizzas best_pizzas = pizza_manager.with_pizzas(restaurant.pizza_set.all()).cheap_pizzas().top_pizzas().get()
There is one caveat though: you cannot run any of the filtering methods unless you have passed in the pizza list first. This can seem obvious, since the manager cannot operate on a non-existing list of pizzas, but this can be a pitfall when programming and you can make a mistake somewhat easily. You cannot do this:
# we are going to get a TypeError here since self.pizzas is None at this point PizzaManager(restaurant).cheap_pizzas()
So basically my question is how to deal with this situation. How can I properly deal with method coupling while having chained methods at the same time? How can I make it clear, from a design point of view, that you must specify list of pizzas the manager is currently going to act upon before runnin any of the filtering methods?
Note that just passing the list of pizzas in the constructor is not a valid option, I don't want to instantiate a single manager every time I want to use a different list of pizzas.