1

I would like to achieve something akin to the strategy pattern in scala without resorting to pattern matching with a long list of case statements. Here is roughly what I have in mind:

trait HandlerTrait {
   def handlerA(...): Unit
   def handlerB(...): Unit
}

SomeClass1 extends HandlerTrait {
   override def handlerA(...) {...}
   override def handlerB(...) {...}
}

SomeClass2 extends HandlerTrait {
   override def handlerA(...) {...}
   override def handlerB(...) {...}
}

object MyApp extends App {
   // 1. define bindings for these implementations
   val myBindings = Map(x -> someClass1, y -> someClass2)

   // 2. Such that implementation of someMethod targeting handlerA implementations could look like this:
   def someMethod(object: ObjectType): Unit = {
      myBindings.get(object.x) match {
        case Some(entry) => entry.handlerA(object)
        case None => ()
      }
   }
}

A few more things:

  1. I don't know how many SomeClassXXX I will have. I will add as needed to provide customizations on how to handle A/B/C ...
  2. Given a key, I want to dispatch to the correct class and execute the targeted handler.

Is there a better more concise way of achieving this in scala?

1 Answer 1

0

I think one way to reduce boilerplate is to use type system rather than inheritance. For instance, if your handler is of type T => Unit then any function that satisfies this type can be a handler, there is no need to officially declare HandlerTrait and even someMethod.

Whether to use a Map or cases to map from a key to a handler is up to you. Both can be extended to handle new cases.

Here is an example to sum up what I'm proposing:

val currentlyDefinedStrategies: PartialFunction[String, Unit] = {
  case "1" => println(1)
  case "2" => println(2)
}

val newStrategies: PartialFunction[String, Unit] = {
  case "3" => println(3)
}

val defaultStrategy: PartialFunction[String, Unit] = {
  case _ => println("default")
}

And usage:

scala> currentlyDefinedStrategies("1")
1

scala> currentlyDefinedStrategies("3")
scala.MatchError: 3 (of class java.lang.String) ...

scala> currentlyDefinedStrategies.orElse(newStrategies)("3")
3

scala> currentlyDefinedStrategies.orElse(newStrategies)("4")
scala.MatchError: 4 (of class java.lang.String)

scala> currentlyDefinedStrategies.orElse(newStrategies).orElse(defaultStrategy)("4")
default

You can achieve similar pattern with Map or using other FP techniques. The main point is to keep the most relevant code and get rid of boilerplate. Of course, HandlerTrait might be useful to you for structuring your code and thinking in terms of classes rather than functions, but the idea is the same.

See also: https://pavelfatin.com/design-patterns-in-scala/#strategy

The above example is a bit simplified and you actually want to pass parameters to handler (println in our case). Here is how:

val currentlyDefinedStrategies: Int => PartialFunction[String, Unit] = (x) => { 
  case "1" => println("1: " + x)
  case "2" => println("2: " + x)
  case _ => println("default: " + x)
}

You can fix the argument without choosing a strategy:

scala> val noStrategy = currentlyDefinedStrategies(1)
noStrategy: PartialFunction[String,Unit] = <function1>

... and provide strategy afterwards:

scala> noStrategy("1")
1: 1

Or apply the strategy right away:

scala> currentlyDefinedStrategies(1)("1")
1: 1

You can also decide on your strategy first and then pass an argument:

val currentlyDefinedStrategies: PartialFunction[String, Int => Unit] = { 
  case "1" => x => println("1: " + x)
  case "2" => x => println("2: " + x)
  case _ => x => println("default: " + x)
}

scala> val handlerWithChosenStrategy = currentlyDefinedStrategies("1")
handlerWithChosenStrategy: Int => Unit = $anonfun$1$$Lambda$1374/666224848@59a9f3eb

scala> handlerWithChosenStrategy(1)
1: 1

I think the point is that FP is so rich and flexible that strategy pattern is really not a thing. It's basically just some function type that suits your convenience like type Strategy[T, -A, +B] = PartialFunction[T, A => B]. Example:

scala> type Strategy[T, -A, +B] = PartialFunction[T, A => B]
defined type alias Strategy

val currentlyDefinedStrategies: Strategy[String, Int, Unit] = {
  case "1" => x => println("1: " + x)
  case "2" => x => println("2: " + x)
  case _ => x => println("default: " + x)
}
currentlyDefinedStrategies: Strategy[String,Int,Unit] = <function1>

scala> currentlyDefinedStrategies("1")(1)
1: 1

A more advanced concept would be an Expression Problem (here) where you need to extend both the operations you can do on types as well as adding new types.

1
  • 1
    This is indeed helpful. Thank you.
    – uneewk
    Commented Oct 19, 2018 at 1:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.