看来您的图书馆正在进行类似数据库的调用。如果是这种情况,那么我将完全按照JPA 2 规范实现。
我的意思是,查看JPAfind()
API 中的方法并准确返回他们在那里所做的事情。
/**
* 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()
方法与您想要的方法不接近,您应该实现与getSingleResult()getCustomer()
相同的行为:
/**
* 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
如果找到多个实例或IllegalStateException
SQL 错误,则会抛出。
你必须决定哪种行为最适合你。
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 制作了一段视频,解释如何设计一个好的 API 以及它为什么重要。