Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to handle invalid arguments in scala

Tags:

scala

I'm writing a function that takes a request object, there are several ways that the request could be configured, but only one valid form, so before I perform my function I'd like to test how the object is configured. If I were doing this in java, I'd write something like this:

static void func(Request request) {
  if (condition1)
    return false

  if (condition 2)
    return false

  if (condition 3)
    return false

  request.process()
  return true
}

In scala though, in trying to avoid using return, I usually end up with this:

static void func(Request request) {
    if (!condition1) {
        if (!condition 2) {
            if (!condition 3) {
                request.process()
                return true
            }
            else
                return false
        }
        else
            return false
    }
    else
      return false
}

This is a simplified form as usually there are things that I need to do after condition 1, and then after condition 2, which mean that I can't just combine the conditions into a single if statement (e.g. condition 1 checks that something isn't null, then condition 2 checks if the value of that thing is valid).

What I'm wondering is how do I make my code clean and readable whilst still having these checks in place?

like image 232
Andy Avatar asked May 02 '19 11:05

Andy


Video Answer


2 Answers

you can use pattern matching

request match {
    case _ if (condition1 || condition2 || condition3) => false
    case _ => request.process(); true
}
like image 108
Shantiswarup Tunga Avatar answered Nov 15 '22 05:11

Shantiswarup Tunga


In Scala it is usual to return Option[value] rather than returning true/false and relying on side effects. And a Request object would normally be pure data, with processing done by an external function.

So a typical Scala function might look like this:

def func(req: Request): Option[Result] =
  req match {
    case Request(a, _, _) if condition1(a) => None
    case Request(_, b, _) if condition2(b) => None
    case _ =>
      Some(processRequest(req))
  }
like image 21
Tim Avatar answered Nov 15 '22 04:11

Tim