dimanche 22 mars 2015

Functional way to implement strategy pattern

I am trying to solve a problem that handles conversion from one Temperature Unit to the other(Celsius, Kelvin, Fahrenheit).


In Java I need to create an interface and provide multiple implementations that encapsulate the Input Type and return the result as a unit of the output type. e.g Kelvin to Celsius or celsius to fahrenheit etc. I have refactored my code in scala to following but still I feel it breaks the Open closed principle, since in case I need to add another type I need to change the existing code.Any suggestions to keep the code functional as well as adherent to the Open closed principle Please ignore the logic for conversion



object TempConverter extends App {

object UnitType extends Enumeration {
type EnumType = Value
val cel, fah, kel = Value
}

def convert(x: Double, i:UnitType.Value,o:UnitType.Value) = {
strategy(i,o)(x)
}

def strategy(inputType: UnitType.Value, outputType: UnitType.Value) = {
inputType match {
case UnitType.cel => celsius(outputType)
case UnitType.kel => kelvin(outputType)
case UnitType.fah => fahrenheit(outputType)
}
}


def celsius(outputType: UnitType.Value) = {
outputType match {
case UnitType.fah => x: Double => x * 1.8 + 32
case UnitType.kel => x: Double => x * 1.8 + 32
}
}

def kelvin(outputType: UnitType.Value) = {
outputType match {
case UnitType.cel => x: Double => x - 273.5
case UnitType.fah => x: Double => x * 1.8 + 32
}
}

def fahrenheit(outputType: UnitType.Value) = {
outputType match {
case UnitType.cel => x: Double => x * 1.8 + 32
case UnitType.fah => x: Double => x * 1.8 + 32
}
}

println(convert(32.0, UnitType.cel, UnitType.fah))

}

Aucun commentaire:

Enregistrer un commentaire