Exercises in Programming Style–Aspects

Yan Cui

I help clients go faster for less using serverless technologies.

NOTE : read the rest of the series, or check out the source code.

If you enjoy read­ing these exer­cises then please buy Crista’s book to sup­port her work.

exercises-prog-styles-cover

Fol­low­ing on from the last post, we will look at the Aspects style today.

 

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.

Constraints

  • 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:

Style18_01

we want to chain them together at the end of the program:

Style18_02

and get the following outputs (note the timing of the function calls have been logged):

Style18_03

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:

Style18_04

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.

Style18_05

 

You can find the source code for this exer­cise here.


 

Whenever you’re ready, here are 4 ways I can help you:

  1. If you want a one-stop shop to help you quickly level up your serverless skills, you should check out my Production-Ready Serverless workshop. Over 20 AWS Heroes & Community Builders have passed through this workshop, plus 1000+ students from the likes of AWS, LEGO, Booking, HBO and Siemens.
  2. If you want to learn how to test serverless applications without all the pain and hassle, you should check out my latest course, Testing Serverless Architectures.
  3. If you’re a manager or founder and want to help your team move faster and build better software, then check out my consulting services.
  4. If you just want to hang out, talk serverless, or ask for help, then you should join my FREE Community.

 


Leave a Comment

Your email address will not be published. Required fields are marked *