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:

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) {
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) {
    } else {

object Main {
  def main(args: Array[String]) {
    val example = new Example

No comments :

Post a Comment