Exercises in Programming Style–Closed Maps

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 Closed Maps style today.

 

Style 12 – Closed Maps

Constraints

  • Larg­er prob­lem is decom­posed into things that make sense for the prob­lem domain
  • Each thing is a map from keys to val­ues, some val­ues are procedures/functions
  • The procedures/functions close on the map itself by refer­ring to its slots

Does the con­straints sound a bit like Javascript? It should, because this style is also known as pro­to­types.

 

First, let’s define what a Map con­sti­tutes to in our solu­tion and the three things we need:

Style12_01

Then let’s add to the dataS­tor­a­geObj map (this is anal­o­gous to the DataS­tor­age­M­an­ag­er in the Things and Let­ter­box styles). Here we’ll map the “init” key to a func­tion that extracts the words from the spec­i­fied path and stores the result as a string[] in the “data” key.

Style12_02

Next, let’s do the same for the stop­Word­sObj map:

Style12_03

and the word­Fre­q­sObj map:

Style12_04

Final­ly, we need to ini­tial­ize both dataS­tor­a­geObj and stop­Word­sObj maps (notice that we need to first cast each val­ue to a func­tion sig­na­ture and then invoke it with an argu­ment, pret­ty ugly…):

Style12_05

and then count any­thing that’s not a stop word, and print the top 25:

Style12_06

These last cou­ple of lines should be encap­su­lat­ed into anoth­er map that’s anal­o­gous to the Word­Fre­quen­cy­Con­troller in the Things style. The rea­son I didn’t do this was because I want­ed to stay faith­ful to Crista’s exam­ple where she chose not to for some rea­son.

 

Whilst this was anoth­er inter­est twist to the OOP par­a­digm that we (as .Net devel­op­ers) are used to, like the Let­ter­box style it’s also very much at odds with how one would idiomat­i­cal­ly approach thing in F#. As a style, we also didn’t get a chance to explore oth­er pos­si­bil­i­ties that often come with this style — name­ly pro­to­typ­al inher­i­tance and mon­key patch­ing.

 

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