Scala Enums: Real Life Example

I wanted to follow up my previous post on Scala Enums with a real-life example. The beauty of this example is my ability to use advanced typing techniques such as type parameters, mixin traits, even a composite pattern, in what basically amounts to a simple enumeration type. This code is quite easy to read, and perfectly conveys my intentions. I don't even want to imagine what I would have done in Java for something like this.

Here's the basic idea behind the code. An Analysis has lots of different columns, which have a class hierarchy like this

  • AnalysisColumn
    • ScoreColumn
      • RawDataScoreColumn
      • ComputedColumn (subclasses not shown)
    • NonScoreColumn
      • InfectionColumn
      • WellColumn
      • VirusColumn

We want to create policies that define whether a column is shown or hidden, for a certain set of columns. We create policies for ScoreColumn, InfectionColumn, WellColumn, and VirusColumn. Each of these policies is a case object. We can look at these as the enumeration values in a Java enumeration. We do need to iterate over these in other places, (e.g., when exposing them in the UI), so we maintain sequences of these values in the ColumnViewPolicy object.

We also want to have column view policies that function over all types of analysis columns. We do this by creating a composite object that contains one policy each of ScoreColumn, InfectionColumn, WellColumn, and VirusColumn. To determine the viewability of a column, the composite delegates to the contained policy corresponding to the type of the column. Pattern matching makes it easy to delegate. We use a case class to implement the composite, which makes a lot of things easy, such as creating a new composite from an old one by replacing one of the contained policies.

No comments:

Post a Comment