0

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)

The 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)

Essentially, the 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 self.pizzas list:

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:

pizza_manager.with_pizzas(all_pizzas).cheap_pizzas().top_pizzas()

Finally, to retrieve the list of filtered pizzas we just run the get() method:

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.

1 Answer 1

3

A common suggestion is to never create an object with invalid state. Pass the list of pizzas to the managers constructor and the problem goes away.

If your requirements are too complex for that to be possible, then the Builder pattern can help: use another object that contains the methods for adding pizzas, which then had a build method that copies them to the manager object and returns it, so your client code would look something like this:

pizza_manager_builder()
     .with_pizzas(some_pizza_list)
     .with_pizzas (more)
     .build()
     .top_selling(5)
     .cheapest ()

The implementation would then be something like:

class pizza_manager_builder:
    pizza_list = []
    def with_pizzas (self, pizzas):
       self.pizza_list.extend(pizzas)
       return self
    def build (self):
       assert len(self.pizza_list) > 0, "must set up new pizza list before invoking build"
       result = pizza_manager(self.pizza_list)
       self.pizza_list = []
       return result

class pizza_manager:
    def __init__(self, pizza_list):
       self.pizza_list = pizza_list
    def top_selling (self, count):
       ...
    def cheapest (self):
       ...
8
  • I don't see at what point we're making sure the filtering methods cannot be called unless the list of pizzas is set?
    – dabadaba
    May 29, 2017 at 14:12
  • Because build returns a different object that contains those methods (but which don't exist until you call build), so you'll get an error if you don't call it. And it should be pretty clear that even you're building the manager object like this you need to provide it's configuration before you can build it, so you shouldn't make such errors in this kind of system. You can even have build fail with an exception if no pizzas are configured between calls. In a static language, you can take this further, by having build in a separate interface that is only visible in the return value of ....
    – Jules
    May 29, 2017 at 16:05
  • with_pizzas, so you'd get a compile time error if you forgot to call it. In a dynamic language this isn't achievable, unfortunately.
    – Jules
    May 29, 2017 at 16:07
  • Well sure I could just throw a ValueError in every single filtering method but that's kind of tiresome.
    – dabadaba
    May 29, 2017 at 17:23
  • Right, but if you use two different objects, one with the configuring methods and a method to return the one with the filtering methods, you don't need to mess around adding exception handling code to each of them, it'll just work because the methods don't exist on the original object.
    – Jules
    May 29, 2017 at 18:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.