Additional Tuple Techniques
Many of the examples we've looked at have either been scalar functions, or
relatively simple structures built from small tuples. We can often exploit Python's
immutable namedtuple as a way to build complex data structures. We'll look at how
we use and how we create namedtuples. We'll also look at ways that immutable
namedtuples can be used instead of stateful object classes.
One of the beneficial features of object-oriented programming is the ability to create
complex data structures incrementally. In some respects, an object is simply a cache
for results of functions; this will often fit well with functional design patterns.
In other cases, the object paradigm provides for property methods that include
sophisticated calculations. This is an even better fit for functional design ideas.
In some cases, however, object class definitions are used statefully to create complex
objects. We'll look at a number of alternatives that provide similar features without
the complexities of stateful objects. We can identify stateful class definitions and
then include meta-properties for valid or required ordering of method function calls.
Statements such as If X.p() is called before X.q(), the results are undefined are outside the
formalism of the language and are meta-properties of a class. Sometimes, stateful
classes include the overhead of explicit assertions and error checking to assure that
methods are used in the proper order. If we avoid stateful classes, we eliminate these
kinds of overheads.
We'll also look at some techniques to write generic functions outside any
polymorphic class definition. Clearly, we can rely on Callable classes to create a
polymorphic class hierarchy. In some cases, this might be a needless overhead in a
functional design.