看来您的库正在执行类似数据库的调用。如果是这种情况,那么我将完全按照JPA 2 specification 的方式执行。
我的意思是,查看JPA API 中的find() 方法并准确返回他们在那里所做的事情。
/**
* Find by primary key.
* @param entityClass
* @param primaryKey
* @return the found entity instance or null
* if the entity does not exist
* @throws IllegalStateException if this EntityManager has been closed.
* @throws IllegalArgumentException if the first argument does
* not denote an entity type or the second
* argument is not a valid type for that
* entity's primary key
*/
public <T> T find(Class<T> entityClass, Object primaryKey);
你在这里看到find,我认为它类似于你的getCustomer()方法,如果没有找到它将返回null,如果参数无效则只抛出IllegalArgumentException。
如果find() 方法与getCustomer() 的方法不接近,您应该实现与getSingleResult() 相同的行为:
/**
* Execute a SELECT query that returns a single result.
* @return the result
* @throws EntityNotFoundException if there is no result
* @throws NonUniqueResultException if more than one result
* @throws IllegalStateException if called for a Java
* Persistence query language UPDATE or DELETE statement
*/
public Object getSingleResult();
如果没有找到结果将抛出EntityNotFoundException,如果找到多个实例则抛出NonUniqueResultException,如果SQL 错误则抛出IllegalStateException。
你必须决定哪种行为最适合你。
getResultList() 也是如此:
/**
* Execute a SELECT query and return the query results
* as a List.
* @return a list of the results
* @throws IllegalStateException if called for a Java
* Persistence query language UPDATE or DELETE statement
*/
public List getResultList();
getResultList() 将返回 null 如果没有找到,并且只在 SQL 非法时抛出异常。
通过遵循这种行为,您将保持一致,并且您的用户会感觉了解图书馆的情况。
另一种行为是返回一个空集合而不是null。这就是Google Guava 实现其 API 的方式,这确实是首选原因。但是,我喜欢一致性,并且仍然认为您应该尽可能接近standard 来实现该库。
资源
Joshua Bloch made a video explaining how to design a good API and why it matters.