Monday, April 15, 2013

Guavas Optional... I know where are you from :)

Consider the example of a function that calculates the square root of x. That's make sense if try to calculate square root of a number which is equal or greater than zero, but what if it isn't? Return -1 or throw exception? This does not sound good... Fortunately google-guava provides more elegant solution, which is Optional class. Let the code speak:
import com.google.common.base.Optional;

public class Example {

    public static Optional< Double > sqrt(Double arg) {
        Optional< Double > result = Optional.absent();
        if(arg >= 0.0) {
            result = Optional.of(Math.sqrt(arg));
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(Example.sqrt(-2.0));
        System.out.println(Example.sqrt(2.0));
    }
}
Returning Optional allow us to explicite showing, than in certain circumstances function can return result which dosen't make sense or it's empty or whatever else. What the best? In Scala, this functionality is part of the language... and it is in quite nice and readable form:
class Example {

  def sqrt(arg : Double) = {
    if (arg>=0) {
      Some(math.sqrt(arg))
    } else {
      None
    }
  }
}

object Main {
  def main(args: Array[String]) {
    val example = new Example
    println(example.sqrt(-2))
    println(example.sqrt(2))
  }
}

No comments :

Post a Comment