Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala Constructor/Method Parameter Checking

Tags:

scala

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).

like image 251
jstnchng Avatar asked Aug 07 '15 18:08

jstnchng


1 Answers

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 Trys from top to bottom.

like image 197
eddiemundorapundo Avatar answered Oct 24 '22 03:10

eddiemundorapundo