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.

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-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.

Constraints

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

Style18_01

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

Style18_02

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

Style18_03

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:

Style18_04

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.

Style18_05

 

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