Exercises in Programming Style–Pipeline

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 Pipeline style today.

 

Style 5 – Pipeline

Although Crista has called this the Pipeline style, you would rec­og­nize it as Func­tion­al Pro­gram­ming.

Constraints

  • Larg­er prob­lem is decom­posed using func­tion­al abstrac­tion. Func­tions take input, and pro­duce out­put
  • No shared state between func­tions
  • The larg­er prob­lem is solved by com­pos­ing func­tions one after the oth­er, in a pipeline

 

Final­ly we’re able to write some idiomat­ic F# code!

 

Functions

The struc­ture of the appli­ca­tion is iden­ti­cal to that of the pro­ce­dur­al style we explored in the last post. Except, this time around we’ll be pass­ing data around as input and out­put, rather than glob­al shared state.

image

and then to tie every­thing togeth­er:

image

 

Conclusions

You might notice that the above code is actu­al­ly very sim­i­lar to what we had in the pro­ce­dur­al style. By remov­ing the use of shared state our func­tions are now idem­po­tent and pro­vide bet­ter encap­su­la­tion.

Final­ly, com­pared to Crista’s solu­tion in Python:

image

the beau­ty of F#’s pipes (|>) idiom real­ly shone through.

 

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