I agree that the null check is not need.
I also agree that the first version is misleading.
I suggest something like :
CurrentDao.java
public MyBean find(...) {
...
query.setMaxResults(1);
List<MyBean> results = query.getResultList();
return ListHelper.firstOrNull(results);
}
ListHelper.java
public <E> E firstOrNull(Collection<E> items) {
if (items == null || items.isEmpty()) {
return null;
}
return items.iterator().next();
}
As an advantage for the extraction of the technical code for finding the first, you can see that:
- the functional code is shorter, clearer (a static import could even go further)
- the technical code will not not repeated, it is reusable.
- the technical code handles all cases (if you forget one, you could add it later without impact on the calling code), and works on any type of Collection (only the iterator is usable).
setMaxResults
. AFAIK the null check is not needed (at least for JDBC). – Landei Aug 29 '11 at 14:24anotherList.add(query.getSingleResult());
in a try/catch. – Gary Buyn Nov 20 '11 at 20:31