Musings about this and that

December 3, 2009

New adventure: try to help out with JSFUnit’s static analysis package

Filed under: JSFUnit — ajesse @ 3:50 pm
Tags: , , ,

It itches too much, so I am trying to scratch.

I have joined the JSFUnit team to help out with the static analysis package. One of the special features of JSFUnit has been orphaned for some time.

November 13, 2009

NPE comparing BigDecimal objects?

Filed under: Uncategorized — ajesse @ 11:55 am
Tags:

After having learned that equals() is not equal enough (my other post) I just replaced equals by compareTo. After studying the Javadoc for BigDecimal.compareTo I did not expect any problems… until some Boundary-value analysis occurred and there the NPE-issue was raised… What a NPE in a simple comparision?

A quick look into the compareTo code showed, what research into the Javadoc confirmed, even though not at the expected place.
The Javadoc for BigDecimal.compareTo(java.math.BigDecimal) did not reveal any pitfalls or precoonditions. Neither did the Javadoc for Comparable.compareTo(T). Nothing about preconditions…
Only in the class-javadoc for Comparable an innocent sentence revealed the source of the problem. Whereas in other places null is just a special case of an Object, Comparable follows this credo:

Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.

So another lesson learned. A pity that this precondition is not documented somewhere. NullPointerException obviously is a RuntimeExcpetion and as such does not need to be documented. But when a method should repsond with such a runtime expcetion to a precondition, this behaviour should be documented as a precondition to the method.

October 27, 2009

When equals() is not equal enough

Filed under: miscellaneous — ajesse @ 1:36 pm
Tags: ,

The other day we were struggling doing comparisions with BigDecimals in a distributed application with BigDecimals originating from different sources. As we had learned we used equals() to compare the objects and even though everything seemed correct, even in the debugger, the logic that indicated an equality condition never was executed.

Check these two methods, and try to predict the outcome:

  private void sample1() {
    BigDecimal one1 = new BigDecimal("1");
    BigDecimal one2 = new BigDecimal("1.000");

    System.out.println("Comparing new BigDecimal(\"1\") and BigDecimal(\"1.000\"):");
    if (one1.equals(one2)) {
      System.out.println("  equals() indicates equality...");
    } else {
      System.out.println("  equals() indicates different values...");
      if (one1.compareTo(one2) == 0) {
        System.out.println("    but comparesTo() thinks the two BigDecimals are equal.");
      } else {
        System.out.println("    and comparesTo() thinks the same.");
      }
    }
  }

  private void sample2() {
    BigDecimal one1 = new BigDecimal(1);
    BigDecimal one2 = one1.setScale(3);

    System.out.println("Comparing new BigDecimal(1) and BigDecimal(1).setScale(3):");
    if (one1.equals(one2)) {
      System.out.println("  equals() indicates equality...");
    } else {
      System.out.println("  equals() indicates different values...");
      if (one1.compareTo(one2) == 0) {
        System.out.println("    but comparesTo() thinks the two BigDecimals are equal.");
      } else {
        System.out.println("    and comparesTo() thinks the same.");
      }
    }
  }

Looking into the Javadoc (Java 5) of BigDecimals gave a first hints:

Note: care should be exercised if BigDecimal objects are used as keys in a SortedMap or elements in a SortedSet since BigDecimal’s natural ordering is inconsistent with equals. See Comparable, SortedMap or SortedSet for more information.

and

Compares this BigDecimal with the specified Object for equality. Unlike compareTo, this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).

That definitely was a bit unexpected, but at least documented.

October 9, 2009

JadeLiquid first impressions

Filed under: JadeLiquid, Unit Testing, UnitTest — ajesse @ 1:24 pm
Tags:

Time to test another testing tool. This time I’ll try to give a commercial tool possibility to convince me: LiquidTest – Agile Functional Testing

The first installation attempt did fail, because the license key sent by mail was distorted by some element in the mail-chain. A call or an email will supply you with a test-file with a working license key.
Once the eclipse plugin is installed and the license activated, you will find a new eclipse perspective and a sample project with the usual test-sample (a call to a famous search engine). Another nice touch is the creation of a new test-class. The plugin immediately offers to enter “record mode”…

to be continued

August 10, 2009

Java Pearls: Really short production ready class

Filed under: Java Pearls — ajesse @ 1:41 pm
Tags:

Browsing through project code for clean up has let us stumble upon this sample of a really short java class:

package some.pkg;
public class CopyParameters {
}

The package this class was found in has already been declared production ready by the developer. Looking for checkstyle violations (missing type javadoc) let us stumble on that class.

August 7, 2009

Java Pearls: the Void class

Filed under: Java Pearls — ajesse @ 12:37 pm
Tags:

Browsing through project code for clean up has let us stumble upon this:

package some.pkg;
import java.io.Serializable;
public class Void4MyProject implements Serializable{
  public static final Void4MyProject NULL = null;
  private Void4MyProject() {
  }
}

I never had the need to have a serializable null-instance. Simply beautifull and creative.

Just for playing… how is it used…

  final protected IAccessor subTable() {
    return new IAccessor() {
      public String getId() {
        return SUB_TABLE;
      }
      public Class getStaticType() {
        return Void4MyProject.class;
      }
      public Void4MyProject getValue(T parent) {
        return null;
      }
      public void setValue(T parent, Void4MyProject value) {
        // nothing to do
      }
    };
  };

Here I consider it a big NoNo that the defined instance of Void4MyProject is not even used.

March 12, 2009

Java Pearls: Why not copy the attribute’s value onto itself

Filed under: Java Pearls — ajesse @ 2:47 pm
Tags:

I like it, when values are set into attributes from where they have been fetched. Makes for readable code.

UserBean deputyChange = myTransferObject.getDeputy();
if (deputyChange != null && deputyChange.getUid() != null) {
  if (!checkUserRole(deputyChange.getUid(), FunctionGroups.ROLE_TO_CHECK.getRole())) {
    throw new IllegalArgumentException("Deputy user-id not valid: " + deputyChange.getUid());
  }
  myTransferObject.setDeputy(deputyChange);
  myContext.getMyBean().getMyOtherTransferObject().setAssistanceUserDetail(deputyChange);
}

Apart from the fact that the webapplications user gets a nice looking Exception Message in his browser if he selected the wrong user from a list… It really makes sense to set the originating attribute to the value it delivered just a few lines above…

March 5, 2009

JSFUnit 1.0.0.GA available

Filed under: JSF, JSFUnit, Unit Testing, UnitTest — ajesse @ 9:47 am

According to the projects website JSFUnit has gone live with release 1.0.0.
Time to get serious about JSF unit testing again.

February 16, 2009

Java Pearls: Pick the first and only item of a collection

Filed under: Java Pearls — ajesse @ 12:40 am
Tags:

Every now and then I stumble upon real nice examples of Java code…

Like this pick method It should return the only item in a collection:

package some.pkg;

import java.util.Collection;
import some.pkg.Helper4Exceptions;

/**
 * Helper for Collections.
 */
public class Helper4Collections {
	public static  E pick(Collection coll) {
		Helper4Exceptions.assertNotNull(coll); // throw a runtime exception if coll is null
		if(1!=coll.size()){
			throw new RuntimeException("zero or more than one element found");
		}
		Helper4Exceptions.assertEquals(1,coll.size()); //runtime exception if not exactly 1 member in coll
		return coll.iterator().next();
	}

	// and other methods
}

Obviously the package and the class comment have been messed with to protect the original author

What impressed me first was the impossibility to reach the call of assertEquals in this method. Then I went further to look at the two used methods…

package some.pkg;

import some.pkg.Helper4Comparison;

/**
 * This helper class contains several static methods that allows to do advanced
 * exception handling. Furthermore it provides certain assertion method similar
 * to the uses methods within junit test. (this has been done becaus the junit
 * test environment is not part of the produtive deployment.
 */
public class Helper4Exceptions {

	/**
	 * Assert equals.
	 *
	 * @param i
	 *            the i
	 * @param j
	 *            the j
	 */
	public static void assertEquals(int i, int j) {
		assertEquals(new Integer(i), new Integer(j));
	}

  /**
   * Assert equals.
   *
   * @param expectedValue
   *            the expected value
   * @param currentValue
   *            the current value
   * @param
   *            element type
   */
  public static  void assertEquals(T expectedValue, T currentValue) {
    assertEquals(expectedValue, currentValue, "");
  }

  /**
   * Assert equals.
   *
   * @param expectedValue
   *            the expected value
   * @param currentValue
   *            the current value
   * @param
   *            element type
   * @param msg
   *            the msg
   */
  public static  void assertEquals(T expectedValue, T currentValue,
      String msg) {
    boolean isEqual = Helper4Comparison.equals(expectedValue, currentValue);
    if (!isEqual) {
      String message = "objects are not equal";
      Helper4Exceptions.assertTrue(isEqual, message + ":\nexpected <"
          + expectedValue + "> \nbut was   <" + currentValue + "> \n"
          + msg);
      thisLineShouldNeverBeReached();
    }
  }

  /**
   * Assert true.
   *
   * @param condition
   *            the condition
   * @param string
   *            the string
   */
  public static void assertTrue(boolean condition, String string) {
    if (!condition) {
      throwRuntimeException("Assertion:\n" + string);
    }
  }

	/**
	 * Assert not null.
	 *
	 * @param object
	 *            the object
	 * @param msg
	 *            the msg
	 */
	public static void assertNotNull(Object object, String msg) {
		if (object == null) {
			throwRuntimeException("assertion: object is null but was expected not to be null. \n"
					+ msg);
		}
	}

	/**
	 * Assert not null.
	 *
	 * @param object
	 *            the object
	 * @param
	 *            element type
	 * @return the not null object
	 */
	public static  T assertNotNull(T object) {
		if (object == null) {
			assertNotNull(object, "");
			throw thisLineShouldNeverBeReached();
		} else {
			return object;
		}
	}

	/**
	 * throws runtime exception "This line should never be reached".
	 *
	 * @return the runtime exception
	 */
	public static RuntimeException thisLineShouldNeverBeReached() {
		return thisLineShouldNeverBeReached(null);
	}

	/**
	 * throws runtime exception "This line should never be reached".
	 *
	 * @param msg
	 *            the msg
	 *
	 * @return the runtime exception
	 */
	public static RuntimeException thisLineShouldNeverBeReached(String msg) {
		return throwRuntimeException("this line should never be reached"
				+ (msg == null ? "" : ":\n" + msg));
	}

	/**
	 * Throw runtime exception.
	 *
	 * @param msg
	 *            the msg
	 *
	 * @return the runtime exception
	 */
	static public RuntimeException throwRuntimeException(String msg) {
		throw new RuntimeException("\n" + msg);
	}

  // and other methods
}

and the method called in this second class

package some.pkg;
/**
 * This class provides several static helper methods for topic Comparison.
 */
public class Helper4Comparison {

	/**
	 * Equals.
	 *
	 * @param value1
	 *            the value1
	 * @param value2
	 *            the value2
	 *
	 * @return true if both values are equal, and considers the different null
	 *         combinations
	 */
	public static boolean equals(Object value1, Object value2) {
		Boolean equals = isEqualCausedByNulls(value1, value2);
		if (equals != null) {
			return equals.booleanValue();
		} else {
			// now we know that both values are not null
			return value1.equals(value2);
		}
	}

	/**
	 * return true if both values are identical or both null, 

	 * false if one value is null and the other is not null, 

	 * returns null if both values are not null.
	 *
	 * @param value1
	 *            the value1
	 * @param value2
	 *            the value2
	 *
	 * @return true, if checks if is equal caused by nulls
	 */
	private static Boolean isEqualCausedByNulls(Object value1, Object value2) {
		if (value1 == value2) {
			// identical values return true (also checks for both null)
			return new Boolean(true);
		} else if (value1 == null || value2 == null) {
			// this means one value is null but the other is not null
			return new Boolean(false);
		} else {
			// means both values are not null, but not identical
			return null;
		}
	}
}

Well, I’m impressed. Especially because this developer told us once, when we proposed some simple solution to another problem, that we would be stone age developers and he was doing better…

I’d really like to hear hat other developers think about these coding samples.

January 27, 2009

Let’s meet in Vienna again – JSFDays 2009

Filed under: JSF, JSFDays — ajesse @ 2:20 pm
Tags: ,

Last years JSFDays in Vienna have been a huge success. The organization was superb and the event definitely focused on JSF. This year the event will be bigger and contains now two tracks. One of them is focused on JSF while the second track has a larger enterprise Java focus. Check out the website.

With JSF 2 on the horizon you definitely should consider making the trip to Vienna. Several of the sessions for JSF will concentrate on that. And who could you tell better about JSF 2 than the guys that shaped it working for the Expert Group. And JSFDays will feature several expert Group members giving you the information from the source.

Let’s meet there and have some fun too. Vienna definitely is a city to enjoy, so consider staying for the weekend as well and discover its many features.

Already booked?

Next Page »

Blog at WordPress.com.