Enter your Email Address:

Delivered by FeedBurner

To get posts delivered to your Email

29 October 2011

Scala - The Scalable Language

I stumbled upon the programming language Scala few months back and haven't got a chance yet to work with Scala (just download Scala last night and installed Eclipse plugin in my laptop this morning). I happen to watch a video on Scala by Martin Odersky. It is a great presentation - both the language and the presenter.

If you are looking for some alternatives for Java, check out Scala. Companies like Twitter and LinkedIn are using Scala in their products and seems like the list is growing day by day.

Scala is both object oriented and functional language and the code compiles into bytecodes which runs on a Java Virtual Machine. The main advantage of writing Scala program is that you will end up writing lesser amount of code as Scala is more expressive than Java. The adoption of Scala is in early stage and i hope (should say, rather want) it replaces Java.

You can find more stuff on Scala from here.

Overview on Scala, might help you to embrace Scala - http://www.youtube.com/watch?v=zqFryHC018k
Geeky Stuff - http://www.scala-lang.org/node/198
Scala Home - http://www.scala-lang.org/

Needless to say, i m so confused on whether i should blog about Java or Scala :-)

28 October 2011

Measuring Time to Minutest Precision With Guava

Other than profiling, have you ever encountered scenarios where you wanted to measure elapsed time from a predetermined past. A simple way of doing is to log the time (milliseconds or nanoseconds) into a long and then find the difference between two points. Here is a simple code.

public static void timer() throws Exception { 
long startMillis = System.currentTimeMillis(); 
for(int i = 0; i < 10; ++i) { 
Thread.sleep(1000);//equivalent to some work/logic 
long endMillis = System.currentTimeMillis(); 
System.out.println("Elapsed Time = " + (endMillis - startMillis));
// if i need to reset the start time, i need to do the following 
// startMillis = System.currentTimeMillis();
}  
}

If you are looking for only time difference between two points, you don't need to actually log the current time. It is enough if you start a clock (your own clock may be) at time t1 and stop it at time t2. If you want to measure time, you end up writing boiler plates. Guava has a little cute API for this.

Stopwatch is a simple API that mimics the functionality of a stopwatch. Here is the reincarnation of above code example.


public static void niceLittleAPI() throws Exception { 
Stopwatch stopWatch = new Stopwatch();  
stopWatch.start();  
for(int i = 0; i < 10; ++i) { 
Thread.sleep(1000);//equivalent to some work/logic  
System.out.println("Elapsed Time = " + stopWatch.elapsedMillis()); 
// if i need to reset the timer/clock, i need to do the following 
//stopWatch.reset(); 
// and my timer resets to zero
                                 // and if you want to stop the Stopwatch, just call
                                // stopWatch.stop();
}
What are the other advantages of using Stopwatch. I think it is an advantage of Stopwatch that it hides completely the mechanism it uses to keep time and in fact the user of the API is free to give his/her own Ticker.

Another nice addon is that you can get the elapsed time in days, hours, minutes, seconds, milliseconds, microseconds and nanoseconds which becomes very handy at times. A word of caution, Stopwatch is not thread safe and you have to figure it out how to make it thread-safe :-).

In order to understand the full power of Stopwatch, you may want to read Javadocs of Stopwatch, Timer and TimeUnit.

In my next post, we will see yet another Guava class and its use.

You may also want to check my previous post on Guava's Postconditions.

27 October 2011

Preconditions - (Java) Guava Collections Library

Fail early. It is applicable in life and programming.

The methods (or functions) are inevitable part of your code. The methods operate on the objects (or state of the system) and has a logic to do. Sometimes, the logic cannot (or rather must not be applied) due to non-availability of data (objects) or data being in an inconsistent state.

Let us take simple IPv4 address validator. Here is the code.

public static boolean isValidIPV4Address(String ipAddress)
{  
boolean isIp = false;
StringTokenizer tokens = new StringTokenizer(ipAddress, "."); if(tokens.countTokens() == 4)
{
// logic to validate ip address
// set isIp to true or false;
}
return isIp;
}

The above code is potentially dangerous if null is passed into the method. It crashes and brings everything to grinding halt. We can fix this by just adding a null check (and we have been often told to do that but we hardly follow it). The code will look something like this.


public static boolean isValidIPV4Address(String ipAddress)
{
                if(ipAddress == null)
                    throw new NullPointerException();
boolean isIp = false;
StringTokenizer tokens = new StringTokenizer(ipAddress, "."); if(tokens.countTokens() == 4)
{
// logic to validate ip address
// set isIp to true or false;
}
return isIp;
}

And thats how you fail early. You validate the inputs (irrespective of the number of arguments) and flag/fail early without changing the state if the arguments (inputs) sound weird. If you still operate on the data that is passed and change the state of the system, you add more pain by pushing the system to an inconsistent state. [Read Effective Java by Joshua Bloch if you haven't read it yet and if you want to be told by a Java expert]

If you think above is a good way, hold on. You have better way.

Guava (Google collection library) has a better way to handle this by using Preconditions. Replace the null check with one line statement and bingo Guava helps you to throw the exception.


public static boolean isValidIPV4Address(String ipAddress)
{  
Preconditions.checkNotNull(ipAddress); 
boolean isIp = false;
StringTokenizer tokens = new StringTokenizer(ipAddress, "."); if(tokens.countTokens() == 4)
{
// logic to validate ip address
// set isIp to true or false;
}
return isIp;
}

If "null" is passed, Preconditions.checkNotNull throws NullPointerException. You can also check for the validity of expression using Preconditions.checkArgument (check out Javadoc). Apart from improving the readability of code (to reduce boiler plates from code), it helps you to fail faster without causing any trouble to the state of the system.

Check out Preconditions. Here is the Javadoc of Preconditions. Don't you think that Preconditions is worth adding in our source code :-)

In the next post, we will see how to measure time with Guava's Stopwatch.