3
votes

Learning Scala and trying to refactor following two functions to remove duplicate logic. Should I be creating a higher order function or something else to avoid duplicate code? Have a few more similar methods with such duplicate code with only difference in calling different Domain methods.

Little confused over refactoring. Using Scala version 2.10

def authenticate = Action(parse.json) { request =>
  val json = request.body
  val input = Json.fromJson[User](json)
  input.asOpt match {
    case Some(m: User) => Ok(Domain.authenticate(m)).as("application/json")
    case None => Ok("bad input")
  }
}

def addUser = Action(parse.json) { request =>
  val json = request.body
  val input = Json.fromJson[User](json)
  input.asOpt match {
    case Some(m: User) => Ok(Domain.addUser(m)).as("application/json")
    case None => Ok("bad input")
  }
}
2
A simple procedural decomposition (writing a private method to capture the common match portion of the two methods) will do fine.Randall Schulz

2 Answers

2
votes

I guess you can do something like( Untested ):

private def common[A](f:User=>A)(request:RequestHeader) = {
  val json = request.body
  val input = Json.fromJson[User](json)

  input.asOpt match {
    case Some(m: User) => Ok(f(m)).as("application/json")
    case None => Ok("bad input")
  }
}

def addUser = Action(parse.json) { common(Domain.adduser)(_) }

def authenticate = Action(parse.json) { common(Domain.authenticate)(_) } 
0
votes

Im new to Scala too but I think we can do something like this. Please correct me if Im wrong.

You can do something like this

def foo(f:Int=>Int,x:Int):Int = {f(x)}
   foo(x=>x+x,3)

So similarly, you can pass the function you want to call into the common function.