Aliasing objects from expensive statements in Scala pattern match

I have an expensive case statement which needs to hit the database to determine a complete match. If there is a match, the result from the aforementioned call must be used to perform further operations:

def intent = {
    case request @ GET(Path(Seg(database :: Nil))) if recordsFrom(database) != Nil =>
        renderOutput(recordsFrom(database))
    case ...
}

I would like to call recordsFrom(database) only once. In the above example, it is called twice. It seems like I should be able to apply some alias to the statement?

Answers


Lawrence, from what I'm seeing you're using Unfiltered to handle a RESTful request but you've also combined a database lookup with that response filtering. I would advise you not to do that. Instead I'd arrange things as following:

val dbReqCommand = new DBRequestCommand(myDbConPool)

def intent ={
  case req @ GET(Path(Seq(database :: Nil))) => dbReqCommand(req, database)
}

Wherein you've encapsulated the db requests in an object that you could substitute out for testing purposes (think integration tests without a DB backend.) Within the request handler you might then put in the response:

Option(recordsFrom(database)) match{
  case Some(value) => OK ~> renderOpupt(value)
  case None => //an error response or Pass
}

That way you might have something along the lines of:

trait DBReqPlan{
  def dbReqCommand: RequestCommand[String]

  def intent ={
   case req @ GET(Path(Seq(database :: Nil))) => dbReqCommand(req, database)
  }
}

which is easier to test against and work with.


What's wrong with:

def intent = {
  case request @ GET(Path(Seg(database :: Nil))) =>
    val records = recordsFrom(database) 
    if(!records.isEmpty){ 
      renderOutput(records)
    } else {
      ...
    }
  case ...

You can move the body of the first case to a different function if you want to avoid having too many nested blocks.


Need Your Help

How to write a string to Amazon S3 bucket?

amazon-s3 amazon-web-services

How can I add a string as a file on amazon s3? From whaterver I searched, I got to know that we can upload a file to s3. What is the best way to upload data without creating file?