If you enjoy reading these exercises then please buy Crista’s book to support her work.
Style 18 – Aspects
You may also know this style as Aspect-Oriented Programming, or AOP for short. I’m a big fan of the paradigm and have often written about it in the past.
- The problem is decomposed using some form of abstraction (procedures, functions, objects, etc.).
- Aspects of the problem are added to the main program without any edits to the source code or the sites that use them.
- An external binding mechanism binds the abstractions with the aspects.
In her example, Crista used Python’s metaprogramming capability to override the original functions with a new version that has the aspects applied already. Let’s see what we can do in F#!
Starting with the abstractions:
we want to chain them together at the end of the program:
and get the following outputs (note the timing of the function calls have been logged):
Unfortunately, if we try to define the same function twice (once for the abstraction, and then again to shadow it with the profiled version) the F# compiler will bark at us.
But, there’s a easy way to get around this.
Remember how, by opening the Checked module all the arithmetic operators are shadowed with versions that does overflow/underflow checks? We can apply the same technique here:
If we just open the Profiled module we’ll shadow the original abstractions with the profiled versions!
Now, if we chain the abstractions together (the call site) we’ll get the output that we expected.
You can find the source code for this exercise here.
I’m an AWS Serverless Hero and the author of Production-Ready Serverless. I have run production workload at scale in AWS for nearly 10 years and I have been an architect or principal engineer with a variety of industries ranging from banking, e-commerce, sports streaming to mobile gaming. I currently work as an independent consultant focused on AWS and serverless.
Here is a complete list of all my posts on serverless and AWS Lambda. In the meantime, here are a few of my most popular blog posts.
- Lambda optimization tip – enable HTTP keep-alive
- You are thinking about serverless costs all wrong
- Many faced threats to Serverless security
- We can do better than percentile latencies
- I’m afraid you’re thinking about AWS Lambda cold starts all wrong
- Yubl’s road to Serverless
- AWS Lambda – should you have few monolithic functions or many single-purposed functions?
- AWS Lambda – compare coldstart time with different languages, memory and code sizes
- Guys, we’re doing pagination wrong