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

Wednesday, April 10, 2013

Passing arguments by value or by name? What's difference?

In Scala there are two ways to pass values to function. You can pass it by name or value. I try to explain and show examples depicting this issue by write equivalent java code. Let's see example class writen in Scala:
class Example {
  var invocationCount = 0

  def byValue(arg: String) = {
    println(arg)
    println(arg)
    println(arg)
  }

  def byName(arg: => String) = {
    println(arg)
    println(arg)
    println(arg)
  }


  def getMessage(): String = {
    invocationCount += 1
    "invocation count: " + invocationCount
  }
}


object Main {
  def main(args: Array[String]) {

    val example = new Example
    println(example.byValue(example.getMessage()))
    println(example.byName(example.getMessage()))
  }
}
... and output:
invocation count: 1
invocation count: 1
invocation count: 1
()
invocation count: 2
invocation count: 3
invocation count: 4
()
As seen in the first case (method byValue), the method getMessage was evaluated only one time, it result was passed to method byValue and then written three times on screen. And in second case it's a little bit different. In simple terms, when arg was passed by name it is look like passing function as a argument like in JavaScript or like a clousure in Groovy. What about do that in Java? Unfortunately it is not possible to do it in such an elegant and readable way in Java, but is possible to simulate. You can do that by using interface. Let's see Java solution:

// IFunction.java
public interface IFunction< T > {

    T call();
}

// Example.java
public class Example {

    private int invocationCount;

    public void byValue(String arg) {
        System.out.println(arg);
        System.out.println(arg);
        System.out.println(arg);
    }

    public void byName(IFunction< String > function) {
        System.out.println(function.call());
        System.out.println(function.call());
        System.out.println(function.call());
    }


    public String getMessage() {
        return String.format("invocation count: %d", ++invocationCount);
    }

    public static void main(String[] args) {
        final Example example = new Example();
        example.byValue(example.getMessage());
        example.byName(new IFunction< String >() {
            @Override
            public String call() {
                return example.getMessage();
            };
        });
    }
}
It look not so pretty as in Scala or Groovy. It remains to wait for Java 8 with Lambda Expressions...

Monday, April 8, 2013

It's time to dive into Scala

After about two years experience in Java, now it's time for something new. I have tried a little bit of Groovy and it was really captivated me but I'm not entirely convinced by idea of dynamically typed language. Therefore I decided to try Scala which is statically typed language. Furthermore Scala provides full support for functional programming. It's all sounds great! I want to describe my attemps and reflections associated with this language on this blog. Sorry for my english, it's poor because I do not have any practical experience with it, and this is yet another reason for creation of this blog. I will be grateful for all the comments and feedback on both the Scala and my english.