Replace conditional logic with strategy pattern

115 Views Asked by At

I have a long conditional logic.Wanted to have an efficient way to do so.

(city, country) match {

("USA","NewYork") => someVal=1.0
("USA","SomeOther")=> someVal =2.0
....
}

I have this look-up logic inside of loop, how do I cleanly do it.May be a multi-key map or stategy pattern in Scala

1

There are 1 best solutions below

3
On

You have some of ways of doing it. Besides the one use used you can try also:

val map1: Map[(String, String), Double]
map1((country, city)): Double // or
map1.get((country, city)): Option[Double]

or

val map2: Map[String, Map[String, Double]]
map2(country)(city): Double
map2.get(country).flatMap(_.get(city)): Option[Double]

Which one is faster? I don't know. You would have to make the benchmarks for your use case. Map is probably faster than match but without benchmarks nobody can tell how much. Which map is faster? map1 or map2? We might guess but without benchmarks for your use cases, it's just guessing.

Unfortunately, until you run it in something like JMH and compare the results, it might be just results for cold JVM.

And, as long as you use String as keys, it would be difficult to suggest some solution like Strategy or anything from GoF, etc, because they rely on either being able to add some property/method to the class to make computation cheaper and/or on the fact that there is finite number of possibilities which unlocks some optimizations.