Good programming practices

New java.util.Objects class will help in everyday code

July 25th, 2011

Java 7 is coming, so it’s worth to see how the new version helps to create clearer code. Here I present some simple but very useful methods of java.util.Objects class. All those methods are static, so you don’t have to create a new object. Using them it’s easy reduce “if” statements or conditional expressions. The following examples show an old and a new code.

First method checks if an object is null. Will be most useful in methods’ arguments validation.

  1. void oldNullCheck(Object o) {
  2. if (o == null) {
  3. throw new NullPointerException("Object must not be null");
  4. }
  5. }
  7. void newNullCheck(Object o) {
  8. Objects.requireNonNull(o, "Object must not be null");
  9. }

Next method helps when you want see object as String but you’re not sure if it isn’t null.
  1. String oldToString(Object o) {
  2. return (o == null) ? "NULL" : o.toString();
  3. }
  5. String newToString(Object o) {
  6. return Objects.toString(o, "NULL");
  7. }

Last method is similar to the one above but for getting hash code. It can be useful when you overwrite the hashCode method.
  1. int oldHashCode(Object o) {
  2. return (o == null) ? 0 : o.hashCode();
  3. }
  5. int newHashCode(Object o) {
  6. return Objects.hashCode(o);
  7. }

The methods above help you handle variable which may be null. I hope using this class, developers will reduce number of unexpected NullPointerException.

That isn’t all methods. It is worth to see Objects class in documentation.

Leave a Response

You must be logged in to post a comment.