微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

原文地址:https://www.jb51.cc/java/126518.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐