Scala: Code Fluency With Functional Composition
Transitioning from a naive approach to a fluent one.
Join the DZone community and get the full member experience.
Join For FreeThis article will discuss the usage of functional composition in Scala to achieve concise and fluent code. It will demonstrate how code can evolve from a naïve approach to a fluent one.
Scenario
We'll write code that describes how to make pizza, which consists of the following steps:
- Mixing ingredients to make the dough
- Kneading the dough to turn it into a smooth dough
- Rolling out the smooth dough to make the base
- Adding toppings on the base to make the base with toppings
- Baking the base with toppings to produce the final product, pizza
In a nutshell, the steps above must be performed in this predefined sequence to work.
Solution 1
The naïve approach would be using comments to flag the chaining of methods:
object PepperoniPizzaRecipe {
/**
* Stage 1: Mix ingredients
*/
def mix(ingredients: List[Ingredient]): Dough = ???
/**
* Stage 2: Knead the dough
*/
def knead(d: Dough): SmoothDough = ???
/**
* Stage 3: Roll out the dough
*/
def rollOut(s: SmoothDough): Base = ???
/**
* Stage 4: Add toppings
*/
def addToppings(s: Base): BaseWithTopping = ???
/**
* Stage 5: Bake pizza
*/
def bake(s: BaseWithTopping): Pizza = ???
}
It goes without saying that, in this solution, the client code is responsible for ensuring the functions are invoked in the correct sequence, like so:
object ClientCode extends App {
val l = List(Ingredient("Pepperoni"), Ingredient("Cheese"))
// The client needs to invoke function in the correct order
val d: Dough = PepperoniPizzaRecipe.mix(l)
val sd: SmoothDough = PepperoniPizzaRecipe.knead(d)
val s: Base = PepperoniPizzaRecipe.rollOut(sd)
val bwt: BaseWithTopping = PepperoniPizzaRecipe.addToppings(s)
val pizza: Pizza = PepperoniPizzaRecipe.bake(bwt)
}
This is pretty bad for both the:
- developer of the API who cannot easily add/remove steps to/from the process without affecting their clients;
client code as it only wants pizza and now needs to know the internals of the process;
Solution 2
In this new version, the function makePizza
abstracts away the details of how to make pizza. Safety is achieved by reducing the visibility of the internals of the process from public to private
functions:
object PepperoniPizzaRecipe {
private def mix(ingredients: List[Ingredient]): Dough = ???
private def knead(d: Dough): SmoothDough = ???
private def rollOut(s: SmoothDough): Base = ???
private def addToppings(s: Base): BaseWithTopping = ???
private def bake(s: BaseWithTopping): Pizza = ???
def makePizza(i: List[Ingredient]): Pizza = {
val d = mix(i)
val sd = knead(d)
val s = rollOut(sd)
val bwt = addToppings(s)
bake(bwt)
}
}
The benefits of the new version can be listed as:
the API developer is free to add/remove steps without affecting their clients;
the client code doesn't have to know the implementation details as it was the case in Solution 1
object ClientCode extends App {
val l = List(Ingredient("Pepperoni"), Ingredient("Cheese"))
// This is now all the client needs to know to make pizza
val pizza: Pizza = PepperoniPizzaRecipe.makePizza(l)
}
While this new implementation is much better than the one in Solution 1, makePizza
lacks fluency: one variable/function call per line. This forces the reader to pay close attention to whether the variable passed into the function is the one created on the previous line before the sequential dependency of the functions can be realized.
This is where Scala functional composition can be a great way to improve things.
Solution 3
Scala provides the andThen
function that can be used in this scenario to make the good code even better.
The main change in comparison to Solution 2 is the return types of private functions. Instead of returning the object created by that particular step, they now return f: A → B
(Function1
trait) where andThen
lives:
object PepperoniPizzaRecipe {
private def mix: List[Ingredient] => Dough = ???
private def knead: Dough => SmoothDough = ???
private def rollOut: SmoothDough => Base = ???
private def addToppings: Base => BaseWithTopping = ???
private def bake: BaseWithTopping => Pizza = ???
def makePizza(i: List[Ingredient]): Pizza = {
mix andThen
knead andThen
rollOut andThen
addToppings andThen
bake apply i
}
}
Notice how makePizza
composes the chaining of functions so fluently that it feels like you're reading a recipe book.
Surely, one could argue that similar fluency could be achieved without functional composition by doing:
def makePizza(i: List[Ingredient]): Pizza = {
bake(
addToppings(
rollOut(
knead(
mix(i)))))
}
But as it can be seen in this example, the fluency of the implementation was lost:
the natural process of making pizza is represented back-to-front in this code as the first line is the last to execute;
it requires the reader to pause the reading for a few moments to make sense out of it.
This post was an attempt to show the positive effect that functional composition in Scala can have in code readability. I hope you enjoyed it.
Opinions expressed by DZone contributors are their own.
Comments