mardi 19 septembre 2017

How to design stateful abstract classes?

What known patterns or practices are there for designing "stateful abstract classes"?

Consider the following example: The abstract class Action represents a single logical step that can be performed at a certain point. It depends on other Actions being performed (dependencies) and can the action can result in a successful or errornous state (which should be stored on the Action object as well).

I'm using Python here, but the question is not limited to the Python language, although I am aware that your answer may vary depending on the language you are accustomed to.

class Action:

  def __init__(self, name, deps):
    self.name = name
    self.deps = deps
    self.error_message = None  # None, str on failure
    self.status_code = None    # int, 0 on success
    self.executed = False

  def execute(self):
    # Prevent execution if not all dependencies are already executed.
    for dep in self.deps:
      assert dep.executed

    # ... Execute the action, subclass may implement this behaviour

    self.executed = True
    # ... set error_message and status_code

I can think of a number of ways to implement the abstract Action class, but none appear as a clean solution to me.

  1. Add an Action.execute_impl() method that can be implemented by subclasses, the return value would be assigned to status_code, an exception's message could be assigned to error_message

  2. Have some other object or method that can execute actions, takes care of checking dependencies and assigning executed, status_code and error_message, Action.execute() would then be purely abstract and implemented by subclasses

  3. Don't expect Action to be subclasses but instead provide an ActionImpl interface with an ActionImpl.execute(action) method. Every Action would then have an ActionImpl. (We assume that the implementation of ActionImpl.execute() needs access to the Action object that it is implemented for)

Aucun commentaire:

Enregistrer un commentaire