Domain Driven Design in python
This is a collection of notes specific to Domain driven design when implemented with python. The structure I have followed is the same than in the main DDD book by Eric Evans.
The building blocks of Model driven design
Isolating the domain
In the context of the layer architecture, (UI, Application, Domain and infrastructure), python makes blurrying the layers particularly easy, with local imports and lack of typings in returns.
A model Expressed in Software
The traversal direction is less important in python than in other languages. The ubiquity of dictionaries for members of the instances/classes/modules makes easy the reverse directions. This flexibility makes the wrong choice less bad though, which is counterproductive long term.
In python they are represented by immutable types, or carefully preserved mutable types. Immutable types in python:
Mutability is often associated with the existence of a hash method, which helps with the use of hash tables for membership in dictionaries and sets, and it is involved in equality as well
Equality is relatively easy to overload, and so is ordering, inheritance and composition. Multiple inheritance is allowed, and aggregates are trivial with the dynamic composition.
Trivial with functions and the lack of overall side effect protection.
Modules and domain layering
Modules follow a standard tree structure as most languages. The domain layering is responsibility of the developer/designer, although the lack of enforcement techiniques (interfaces, static class definitions or abstract classes) can make a good design harder to archieve
The Life cycle of a Domain object
Aggregates , Factories and Repositories
In general the distinction on the serialised versus the in memory representation of the objects is well defined. Python offers many ways to serialise objects, most of with come with standard python
- dictionaries + JSON or YAML
- ORM (sqlalchemy, djangoorm)
Using The language: An extended example
Refactoring towards Deeper insight
Making implicit concepts explicit
Specifications: In python they are easier to implement than in java, most of the examples given had to deal with java type system clunkyness.
For example, the book DDD (308) defines AbstractSpecification and the subclasses for Or, And and Not operators. All of these operations can be implemented in python via
__or__ and some class level factory for not.
Maintaining Model integrity
Explains the usage of bounded contexts. Python is not particularly affected by this. Perhaps the dynamic nature of function signatures makes signature mismatch harder (which is one of the signs of false cognate)