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?
you can use pattern matching
request match {
case _ if (condition1 || condition2 || condition3) => false
case _ => request.process(); true
}
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))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With