Designing Systems with Aspect Oriented Programming

What is Aspect Oriented Programming?

Aspect Oriented Programming is a programming construct or paradigm which is used to increase modularity of code by adding/modifying the code at run-time.

Aspect Oriented Components

Aspect Oriented Programing: Case Study

Consider the above diagram . This could be any mid sized system ,  let’s assume it has three parts:

  • HTTP server: for serving http based front end clients.
  • WebSocket server: for providing live streaming information to socket based clients.
  • Background Task processors: for running long running operations(like reporting, bulk processing etc.)

The above components depend on smaller components which provide different functionalities.

  • Database Transaction Support
  • Logging
  • Data Validation
  • Internationalization
  • Caching
  • Data Pipeline Sync
  • Real Time Processors

All the above mentioned functionalities are big enough to have a proper implementations, however are not large enough have their own package created separately.

These type of things generally end up in a generic utils package which more often that not ends up becoming a mess as the codebase grows.

Going the AOP way

Instead of writing modules, make aspects out of them. That’s a fancy way of saying make registrable objects out of them(which can be manipulated).

If I was using a purely object oriented programming construct I would end up writing something like this(Note: Code just for an example, will not work)

While this works perfectly, this ends up tying a lot of code and functionality to the HTTP class itself.

If I was doing this using Aspect Oriented Programming , I would just have to register all aspects with this object and this would be compiled and invoked at runtime.

It would end up looking something like this

We are essentially are making a list of functionalities and compiling objects out of it. This design process forces us to write loosely coupled modular code.

Final verdict

You could essentially do everything that you do in Aspect oriented programming under a OOP construct as well(and it would work great).

However I like AOP as a programming paradigm, and it’s ability to keep everything separated.  AOP along with other programming constructs like Finite State Machines(will look at these in another article) can make for cleanly segregated code.

Further

Java has an amazing package called AspectJ (it provides enough documentation to make a gravity warp drive , except telling people how to exactly do AOP) however there is no equivalent package in python for doing the same.

There are meta classes which give you meta programming capabilities. I’ll follow up with a proper tutorial on how to do MetaProgramming in Python.

I am a developer and tech enthusiast based out of New Delhi, India. I love python , have a love-hate relationship with Javascript, and feel that filing out tax forms are easier than Java.

Leave a Reply