Exercises in Programming Style–Aspects

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.


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-Ori­ent­ed Pro­gram­ming, or AOP for short. I’m a big fan of the par­a­digm and have often writ­ten about it in the past.


  • The prob­lem is decom­posed using some form of abstrac­tion (pro­ce­dures, func­tions, objects, etc.).
  • Aspects of the prob­lem are added to the main pro­gram with­out any edits to the source code or the sites that use them.
  • An exter­nal bind­ing mech­a­nism binds the abstrac­tions with the aspects.


In her exam­ple, Crista used Python’s metapro­gram­ming capa­bil­i­ty to over­ride the orig­i­nal func­tions with a new ver­sion that has the aspects applied already. Let’s see what we can do in F#!

Start­ing with the abstrac­tions:


we want to chain them togeth­er at the end of the pro­gram:


and get the fol­low­ing out­puts (note the tim­ing of the func­tion calls have been logged):


Unfor­tu­nate­ly, if we try to define the same func­tion twice (once for the abstrac­tion, and then again to shad­ow it with the pro­filed ver­sion) the F# com­pil­er will bark at us.

But, there’s a easy way to get around this.

Remem­ber how, by open­ing the Checked mod­ule all the arith­metic oper­a­tors are shad­owed with ver­sions that does overflow/underflow checks? We can apply the same tech­nique here:


If we just open the Pro­filed mod­ule we’ll shad­ow the orig­i­nal abstrac­tions with the pro­filed ver­sions!

Now, if we chain the abstrac­tions togeth­er (the call site) we’ll get the out­put that we expect­ed.



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