Thursday, September 24, 2009

Loose Coupling Decorators

Many programming languages offer the ability to decorate certain constructs such as functions or methods. What exactly is a decoration in this context? It is referred to as a decorator because the function or method declaration looks as though it is being decorated. The name is syntactically descriptive. So, having said this, what exactly is a decorator? In Python, a decorator is essentially a function that is used to take an existing function or method and return a transformed version of it. The @ symbol denotes a decorator in Python and is placed above the function or method definition.

So how does this help the developer? Why would they want to take a perfectly normal function definition and put some strange syntax around it? The main purpose for this being that it serves as a factory that can inject objects into the function from other name spaces. This is useful because it allows some developers to define decorators and others can define functions and methods that use them. This supports loose-coupling because the same decorators can be used for many functions. Additionally, a function may be decorated by many decorators.

The effect here is similar that of inheritance. However, these can be difficult to achieve sometimes with inheritance if a strict hierarchy isn't thought up from the onset. The polymorphic operations all need to be consistent with one another using this approach.

The inheritance approach to loose-coupling is probably a superior design to using decorators throughout an application. It is cleaner and provides more consistency. However, if this isn't the initial approach taken and there simply isn't enough time to design a resilient class hierarchy, the decorator approach is a good candidate to achieve loose-coupling.