Thursday, 28 March 2013

Guava : Using Java Collections the Google Way

Recently Guava came out with release 14.0.1 which include a number of bug fixes and enhancements. As a utility library, Guava provides an impressive list of extensions and tools for using Java collections with an aim towards improving code readability, transparently managing Java collections and introducing useful checks and frequently used utility methods that simplify the generation of quality code.
With respect to Java Collections, Guava provides utility methods for creating Immutable collections, and provides some new Collections. If just looking for implementing various checks on your Java Collections, there are a number of Collection Utilities that allow you to create an equivalent Java Collection while writing code that is cleaner and easier to read.

For example, constructing a generic collection before Java 7 would amount to the following line of code:
  • List list = new ArrayList();

In Guava, this could be simplied to  List list = Lists.newArrayList();
And this approach could be further extended to include the List size and initialise the List as follows:
  • List list = Lists.newArrayList(100); // create a list with a 100 elements.
  • List list = Lists.newArrayList("red","blue","green"); // create and initialise a list with some values
Similarly Guava has many utility methods for dealing with nulls in Collections, managing String and performing operations on the Java Math library that is not available in the JDK. If using the Apache Commons Library, Guava is definitely worth a check out !!

Monday, 11 March 2013

ZK 6.0 and the MVVM pattern

Previously I wrote about my experience in using ZK, an event driven UI framework that simplifies UI development for J2EE applications. Currently, the latest release of ZK is 6.5.1.2 which came out in December, 2012. The transition from version 5 to 6 was significant as it included a number of new features, including an upgrade in the jQuery library from 1.4 to 1.6, the use of Advanced templates, new controls and finally most notably among all these changes, the ability to use a new data binding approach called the ZK Bind which was based on the MVVM pattern.
While the MVVM pattern is not a new concept, its introduction in ZK is certainly timely and serves to simplify the development and maintainability of the user interface code. Since ZK is an event-driven framework, it has component which generate events and these in turn need to be handled by the controller which in turn lead to interactions with the model. In ZK 5, the model needed to know about the different components, which were generating events. In ZK 6.0, this layer of interaction has been made transparent  via an implementation of the MVVM pattern, which uses annotions in the ZUL and the model class to tie the components, their events and the model objects all together.
This example is a very simple introduction to the basic approach of using MVVM in ZK. As evident, in the ViewModel: HelloViewModel.java, there is no need for the model to know about the different components it needs to interact with as was the case in ZK 5. The annotations in the ZUL page and the model class wire the components, the events generated and the changes in the model all together without the need for any Java  code to be written.
While applying the annotations and the new approach in building UIs, might take some getting used to, there is no doubt that the implementation of the MVVM pattern using the Binder (ZK Bind) simplifies the UI development and code maintenance. It also provides a cleaner separation of the user interface from the business objects.

Saturday, 2 March 2013

Being Agile : Should I be in a Scrum or work on a Kanban?

After having worked in the Scrum philosophy for several projects, I recently got the opportunity to experience the Kanban way of being Agile. While there are several common between the two flavours of Agile, the overall focus of the two modes is what is the biggest differentiators. In Agile, the focus is on the quantity of work that is delivered while in Kanban, the focus is more on quality.Kanban limits the work in progress with a goal of reducing multi-tasking and maximising output. When working in a Kanban system, the term Flow of Value describes how current work can give maximum returns.Measuring the output of Kanban teams is done in terms of an established Cadence that recognises the ability of a team to deliver high quality work consistently.

The following table gives some comparison points between the Scrum and the Kanban philosophies.

Scrum Kanban
Focus is on quantity of work delivered in a sprint. Focus is on quality of work delivered in a phase or cycle.
There are no Iterations and the need for Estimations is not high.
New stories can be started while others are in progress. Emphasis is given on completing in-progress stories with a priority for fixing bugs that come up in existing  stories.
Team members have clearly defined roles,
such as Scum-Master, Product Owner.
No such roles are maintained.
Different meetings such as Pre-planning meetings and Retrospectives have significant bearing on the sprints Meetings are called as and when required.

After 6 months of employing the Kanban approach, there were some immediate gains visible. Since there were no sprint failures, the morale of the team got a boost which in turn led to greater productivity. Since the WIP limits were strictly adhered to, there was some buffer time which gave rise to the opportunity to focus on creating more unit tests, upgrading to recent versions of developer tools or helping reduce bottle necks in am existing Kanban. While the idea of downing tools and not starting anything new might sound incredulous to a lot of people, slide 9 in this presentation comparing Kanban to Scrum gives a good guide on managing idle team members. Obviously the Kanban approach requires more discipline and trust among team members but if applied in the correct way, can help achieve some immediate goals.

Sunday, 10 February 2013

Testing Private methods using Reflection

Without entering into a debate of why or why not private methods should be directly tested, here are the various steps involved in testing a private method using Java Reflection.

Scenario 1 : The private method has no input parameters, operates on a private variable and returns a value.

The class to be tested.

package com.john.exeriment;

/**
 * The class to be tested.
 *
 */
public class App
{
private String name= "John";
private int numCharactersInName = 0;
 
public int getNumCharactersInName() {
return numCharactersInName;
}
private int getSizeOfName()
{
numCharactersInName = name.length();
return numCharactersInName;
}
public static void main( String[] args )
 {
App app = new App();

System.out.println(" The size of the name is " + app.getSizeOfName());

   }
}
-------------
JUNIT Class

package com.john.exeriment;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * Unit test for simple App.
 */
public class AppTest extends TestCase
{
    /**
     * Create the test case
     *
     * @param testName name of the test case
     */
    public AppTest( String testName )
    {
        super( testName );
    }

    /**
     * @return the suite of tests being tested
     */
    public static Test suite()
    {
        return new TestSuite( AppTest.class );
    }

/**
* Test method operates on the private field using its default value
**/
public void testAppMethod() throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, NoSuchFieldException
    {
    App myApp = new App();
        Method m = myApp.getClass().getDeclaredMethod("getSizeOfName", null);
        m.setAccessible(true);
        Integer size = (Integer) m.invoke(myApp, null);

    assertTrue( "Size should be ", size == myApp.getNumCharactersInName());
    }

We assume the method getNumCharactersInName() has been tested.


/**
* Test case modifies the private field of the class using Reflections before testing the required private method.
**/
public void testAppField() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException, NoSuchMethodException, InvocationTargetException
    {
    App anotherApp = new App();
    Field field = anotherApp.getClass().getDeclaredField("name");
    field.setAccessible(true);
    field.set(anotherApp, "Testing!!!");
   
    Method m = anotherApp.getClass().getDeclaredMethod("getSizeOfName", null);
         m.setAccessible(true);
         Integer size = (Integer) m.invoke(anotherApp, null);
   
    assertEquals( "Size should be", 10,  size, 0.000001 );
    }

}



Scenario 2 : The private method takes a String as an input parameter and does not return a value.

We add the following method to our class.


private void getSizeOfName(String name)
{
numCharactersInName = name.length();
}


And to test it, we have the following JUNIT test.

public void testAppMethodWithInputParam() throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
    App myApp = new App();
   
    // The parameter type
    Class[] parameterTypes = new Class[1];
        parameterTypes[0] = String.class;
        
        // The parameter value
        Object[] parameters = new Object[1];
        parameters[0] = "Cricket";
        
        Method m = myApp.getClass().getDeclaredMethod("getSizeOfName", parameterTypes);
        m.setAccessible(true);
        m.invoke(myApp, parameters);

    assertEquals( "Size is greater than 0", 7, myApp.getNumCharactersInName());
  }


In the test, we set up a String variable which we initialise to the value Cricket, and test if the method initialises the numCharactersInField correctly to 7 characters.

Thus, testing private methods via Reflection is a straightforward process and should be used if there are key parts of the business logic embedded in private methods.