Some class design principles

When defining a class, we have the following sources of attributes and methods:

  • Any decorators applied to the class definition. These are applied to the definition last.
  • The body of the class statement.
  • Any mixin classes. These definitions tend to override the base class definitions in the method resolution order algorithm.
  • The base class. If unspecified, the base class is object, which provides a minimal set of definitions.

These are presented in order of their visibility. The final changes from a decorator overwrite everything below it, making these changes most visible. The body of the class statement overrides anything inherited from mixins or the base class. The base class is the last place used to resolve names. 

We need to be cognizant about how easy it is for software maintainers to see each of these. The class statement is the most obvious place for someone to look for the definition of an attribute or methods. The mixins and the base class are somewhat less obvious than the class body. It's helpful to make sure that the base class name clarifies its role and uses terminology that is clearly essential. For example, it helps to name base classes after real-world objects.

The application of the decorator to the class can lead to obscure features. A strong focus on one or a few features helps to clarify what the decorator does. While some aspects of an application can be suitable for generic decorators, the lack of visibility can make them difficult to test, debug, and maintain.

The mixin classes will generally define additional interfaces or behaviors of a class. It's important to be clear about how the mixin classes are used to build the final class definitions. While a docstring class is an important part of this, the overall docstring module is also important to show how a proper class can be assembled from the various parts.

When writing the class statement, the mixins are listed first, and the essential superclass is listed last. This is the search order for name resolution. The last listed class is the class that defines the essential is-a relationship. The last class on a list defines what a thing IS. The previous class names can define what a thing DOES. The mixins provide ways to override or extend this base behavior.

Aspect-oriented programming is discussed in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset