Good programming practices

Concise Java code

April 22nd, 2012

Here is an example how concise Java code can be. I wrote 2 methods that do the same, but looks different. It checks if an Iterable object has only one object, which is additionally equals to the one passed as the second argument. Both methods use Objects class added in Java 7. The first method use “&&” operator, which evaluates expression on right only when the left one was true.

  1. static <E> boolean containsOnlyOne(Iterable<E> iterable, E object) {
  2. Iterator<E> it;
  3. return (iterable != null) && (it = iterable.iterator()).hasNext() &&
  4. Objects.equals(it.next(), object) && !it.hasNext();
  5. }

Look also at the excerpt (it = iterable.iterator()).hasNext(). The result of the method iterator() is assigned to the variable it, which is then used by invoking hasNext() on it. Below is equivalent method for better understand of the code.

  1. static <E> boolean containsOnlyOneLongVersion(Iterable<E> iterable, E object) {
  2. if (iterable == null) {
  3. return false;
  4. }
  5. Iterator<E> it = iterable.iterator();
  6. if (it.hasNext()) {
  7. E next = it.next();
  8. if (!it.hasNext()) {
  9. return Objects.equals(next, object);
  10. }
  11. }
  12. return false;
  13. }

Both methods pass the following test:

  1. @Test
  2. public void testContainsOnlyOne() {
  3. assertTrue(containsOnlyOne(Collections.singleton("any"), "any"));
  4. assertTrue(containsOnlyOne(Collections.singleton(null), null));
  5. assertTrue(containsOnlyOne(Collections.singletonList(537.82), 537.82));
  6. assertFalse(containsOnlyOne(Arrays.asList("one", "two"), "one"));
  7. assertFalse(containsOnlyOne(Collections.emptySet(), "none"));
  8. assertFalse(containsOnlyOne(Collections.emptySet(), null));
  9. assertFalse(containsOnlyOne(Collections.singletonList("some"), "other"));
  10. assertFalse(containsOnlyOne(Collections.singleton(1471092), 293875));
  11. assertFalse(containsOnlyOne(null, null));
  12. assertFalse(containsOnlyOne(null, 1383));
  13. }

Leave a Response