java – 正确处理返回数据

我正在处理我正在为一个项目写的DAO库的回报的问题.这个图书馆可能会被另一个人使用,我想要正确地做.我应该如何处理我的DAO函数的返回语句?

实施例1
我有函数getCustomer应该返回String.如果一个查询不返回任何结果应该返回null,一个空字符串或者抛出某种异常?

实施例2
我有一个函数getCutomerList,它返回一个类型为ArrayList< String>的值.如果一个查询不返回任何结果应该返回null,一个空的ArrayList或者抛出一些异常?

实施例3
检测到一些sql异常,应该怎么做,抛出异常或尝试try.catch的块可以发生?

在我的情况下,什么是“好”的做法或“最好”的做法?

解决方法

看来你的图书馆正在做数据库式的电话.如果是这样,那么我会做的是 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,这是真正的首选.但是,我喜欢一致性,仍然认为你应该尽可能接近标准来实现图书馆.

资源

Joshua Bloch made a video explaining how to design a good API and why it matters.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...