Saturday, September 22, 2012

Elegantly Implement permutation with Java

The following code is to implement a permutation in a given string with recursive method invoke. Just a few line is enough.



public class Permutation {

/**
 * @param args
 */
public static void main(String[] args) {
 // TODO Auto-generated method stub
 permutedHelper(args[0], "");
}

/**
 * recursively invoke this method to permute from non-permuted string into
 * finished string which is permuted.
 */
private static void permutedHelper(String nonpermutedStr, String finishedStr) {
 if (nonpermutedStr.length() == 1) {
  System.out.println(finishedStr + nonpermutedStr);
 } else {
  for (int index = 0; index < nonpermutedStr.length(); index++) {
   char current = nonpermutedStr.charAt(index);
   String updated_nonpermutedStr = nonpermutedStr.substring(0,
      index) + nonpermutedStr.substring(index + 1);
   permutedHelper(updated_nonpermutedStr, finishedStr + current);
  }
 }

  }
  
}



Thursday, September 20, 2012

How to use Junit Rule -- A powerful Junit feature

Junit has a powerful feature  called@Rule annotation.

The purpose of the @Rule annotation is to mark public fields of a test class. These fields must be of type TestRule(new API, previous one is MethodRule), or an implementing class. Such TestRule behave similar to a AOP aspects, of course without use of any AOP library and specialized for Tests. They can execute code before, after or instead of a test method. Example use cases listed in the release notes include:


  • Notification on tests
  • Setting up or tearing down resources, especially when they are used in multiple test classes
  • Special checks performed after every test, possibly causing a test to fail.
  • Making information about the test available inside the test

Let's take a look at how to use it:

Assuming we have to a bunch of test cases, each has a name with a pattern like test[Method]By[People], the suffix is the author who write this test case. But we want to execute a group of test cases by the same people. But we don't want to change comment the unnecessary code.
Therefore, we have a choice of using the Junit Rule to implement this requirement.

First we create a class to implement the Interface TestRule. The constructor takes the author name that we want to test. The method apply() use java regular expression Pattern to do the filter. If we find the author name appear at the end of method name to be tested, just leave it as before. Otherwise, we create an anonymous class implementing abstract class Statement.

See the code:
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import junit.framework.AssertionFailedError;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

public class MethodMatcherRule implements TestRule{
    
 private String author;
 MethodMatcherRule(String author){
     this.author=author;
    }
 @Override
 public Statement apply(Statement base, Description description) {
  // TODO Auto-generated method stub
  Pattern pattern=Pattern.compile(author+"$",Pattern.CASE_INSENSITIVE);
  Matcher matcher=pattern.matcher(description.getMethodName());
  if(matcher.find()){      
     return base; 
  }
  return new Statement(){             
   @Override
   public void evaluate() throws Throwable {
    // TODO Auto-generated method stub
    throw new AssertionFailedError("Sorry we don't test this method");
       
   }
   
   
  };
 }

}

How to use this rule is really simple.
Step one: Create a public attribute of your rule.
Step two: Instantiate the field you just create.
Step three: Write an annotation @Rule before you field.
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import org.junit.Rule;
import org.junit.Test;

public class SimpleTestCases {

 @Rule
 public MethodMatcherRule rule=new MethodMatcherRule("Tom");
 

 @Test
 public void testAByTom() {
  assertTrue(true);

 }

 @Test
 public void testBByTom() {
  assertFalse(false);
 }

 @Test
 public void testByABC(){
  assertEquals(new Integer(11),new Integer(11)); 
 }
 
 @Test
 public void testAByJim() {
  assertFalse(false);

 }
}



Friday, September 14, 2012

Why we need inner class in Java

Introduction:
 This article is to explain why we need inner class in Java. Then give a very simple example for this purpose with live code.

In java, we typically define one class per file. But java also supports inner class functionality which we don't use it very frequently at the entry-level programming. As we deeply dive into more complicated java framework, we will find inner class is pretty useful and handy.

First, I would like to show a pretty simple data structure--a collection that can store any type of comparable object.
import java.util.Iterator;

public class OrderedCollection<E extends Comparable<? super E>>  {
 
 
 public Iterator<E> iterator() {
  return this.new OrderedCollectionIterator();
 }

 /**
  * the maximum size of the element array
  */
 private final static int MAX = 1000;

 private int currentPoint = -1;
 private Object[] objects;

 public OrderedCollection() {
  objects = new Object[MAX];
 }

 public boolean isEmpty() {
  return currentPoint == -1;
 }

 public void makeEmpty() {
  for (int i = 0; i <= currentPoint; i++) {
           objects[i]=null;
  }
  currentPoint = -1;
 }

 public void insert(E obj) {
  currentPoint++;
  objects[currentPoint] = obj;

 }

 public void remove(E e) {

  boolean flag = false;
  for (int i = 0; i <= currentPoint; i++) {

   if (e.equals(objects[i])) {
    flag = true;
    continue;
   }
// move the later elements forward to replace the removed element value
// set the duplicated element to null
   if (flag) {
    objects[i - 1] = objects[i];
    objects[i] = null;
   }

  }
// set the pointer minus one
  if (flag)
   currentPoint--;

 }

 public boolean isPresent(E e) {

  for (int i = 0; i <= currentPoint; i++) {
   if (e.equals(objects[i])) {
    return true;
   }
  }

  return false;
 }
 public int size() {
  return (currentPoint + 1);
 }

 public E findMax() {
  if (isEmpty())
   return null;

  @SuppressWarnings("unchecked")
  E max = (E) objects[0];
  for (int i = 0; i <= currentPoint; i++) {
   @SuppressWarnings("unchecked")
   E ele = (E) objects[i];
   if (ele.compareTo(max) > 0) {
    max = ele;
   }
  }

  return max;
 }


}

Then I want this data structure implementing a Iterable interface. That means this data structure should have an iterator() method which return an iterator object. With the mentioned iterator object, we can visit each element within this object using hasNext(), next() method.
private class OrderedCollectionIterator implements Iterator<E> {

  int index = -1;
  boolean isDeleteFlag = false;

  @Override
  public boolean hasNext() {
   // TODO Auto-generated method stub
   return (index + 1) <= currentPoint;
  }

  @SuppressWarnings("unchecked")
  @Override
  public E next() {
   // TODO Auto-generated method stub
   index++;
   isDeleteFlag = false;
   return (E) objects[index];
  }

  /**
   * delete the last element returned in the iteration
   */
  @SuppressWarnings("unchecked")
  @Override
  public void remove() {
   // TODO Auto-generated method stub
   if (isDeleteFlag == false) {
    OrderedCollection.this.remove((E) objects[index]);
   }
   isDeleteFlag = true;
  }

 }