I wanted to check some best practices of Scala programming, since I am new to Scala. I read online about how Scala doesn't typically use exceptions except for "exceptional" circumstances (which doesn't include parameter checking). Right now in my project I am using a lot of require
, so I am wondering what the better way of type checking would be.
For example, if I have a class
class Foo(String bar){
require(StringUtils.isNotEmpty(bar), "bar can't be empty")
}
what are my alternatives to checking bar? Do I create a companion object like so
Object Foo {
def apply(bar: String) = Try[Foo] {
bar match = {
case null => Failure("can't be null")
//rest of checks
case _ => Success[Foo]
}
}
Or should I use Option instead?
In addition, for scala methods, how do I check the parameter of the method? If I already return an Option, do I just return an empty Option if I get a bad parameter? Wouldn't that mean I have to check for an empty Option when I use the return of the method and wouldn't throwing an exception allow for a more specific message? (e.g. runtime exception can't use nulls).
I think the Success part of your companion object would return the Foo() object as well?
Object Foo {
def apply(bar: String) = Try[Foo] {
bar match = {
case null => Failure("can't be null")
//rest of checks
case _ => Success[Foo](new Foo(bar))
}
}
To use it you might do something with the Success
you get from Foo(bar):
val hehe = Foo(bar).map(foo => foo.someString()).getOrElse('failed')
The Try methods will automatically wrap exceptions generated by someString() or whatever else that you're doing inside it inside Failures. If you wanted to check the parameters of foo.someString()
, you'd do something similar to your apply()
method. It isn't that much different than throwing exceptions on conditions but I think it's nicer cause the "catch blocks" would be in recover()
or recoverWith()
. You can always exit the Try
using getOrElse()
if your code wasn't designed to chain Try
s from top to bottom.
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