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.

Advertisements

One Comment on “Java Pearls: Pick the first and only item of a collection”

  1. ioss says:

    What I do not understand, is why not use recursion on isEqualCausedByNulls?

    private static Boolean isEqualsCausedByNulls(Object value1, Object value2) {
    if(value1==value2) {
    return Boolean.TRUE; // sorry I just could not use the ctor….
    } else if(value1 == null) {
    // value2 can not be null, so recurse into the method to have some code reuse
    return isEqualsCausedByNulls(value2, value1);
    } else if(value2 == null) {
    return Boolean.FALSE;
    } else {
    return null;
    }
    }

    et voila we got rid of the error prone || operator

    Freue mich auf weitere Perlen,
    Imre


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s