Java Pearls: assertNotNull() – the expert version

Recently a colleague stumbled upon this pearl doing a production code review:

/**
 * 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();
	} 
	return object;
}
/**
 * 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);
	}
}

well at least it is a generic method 🙂

The commenting is also from the production code… Hell of a expert developer.

Advertisements

Java Pearls: Really short production ready class

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.


Java Pearls: the Void class

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.


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

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…


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

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.