Ser*_*hiy 10 java dao api-design behavior
我有一个问题,正确处理我正在为一个项目编写的DAO库的返回.这个库可能会被其他人使用,我想要正确地使用它.我应该如何处理DAO功能的返回声明?
示例1 我有getCustomer函数应该返回String.如果查询没有返回任何结果,我应该返回null,空字符串或抛出某种异常?
示例2
我有一个函数,getCutomerList
它返回ArrayList <String>类型的值.如果查询没有返回任何结果我应该返回null,一个空的ArrayList或抛出一些异常?
示例3
检测到一些SQL异常,我应该怎么做,抛出异常或执行可能发生的块的try
..catch
在我的案例中适用的"好"做法或"最佳"做法是什么?
She*_*ari 10
看来您的库正在进行类似数据库的调用.如果是这种情况,那么我将完全按照JPA 2规范实现.
我的意思是,查看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);
Run Code Online (Sandbox Code Playgroud)
你在这里看到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();
Run Code Online (Sandbox Code Playgroud)
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();
Run Code Online (Sandbox Code Playgroud)
getResultList()
如果没有找到则返回null,如果SQL是非法的,则只抛出异常.
通过遵循此行为,您将保持一致,并且您的用户将会感觉知道库是如何的.
另一种行为是返回空集合而不是null
.这就是Google Guava实现其API的方式,而这正是首选的原因.但是,我喜欢一致性,并且仍然认为你应该尽可能地实现库standard
.
Joshua Bloch制作了一个视频,解释了如何设计一个好的API及其重要性.
归档时间: |
|
查看次数: |
1725 次 |
最近记录: |