正确处理返回数据

发布于 2024-10-16 00:40:25 字数 1431 浏览 3 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

蹲墙角沉默 2024-10-23 00:40:25

看来您的图书馆正在进行类似数据库的调用。如果是这样的话,那么我将完全按照 JPA 2 规范实现的操作。

我的意思是,看看 JPAfind() 方法a> 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() 方法与您想要的 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 制作了一个视频,解释如何设计良好的 API 及其重要性

It seems your library is doing database-like calls. If that is the case, then I would do exactly what is implemented by the JPA 2 specification.

What I mean by that is, look at the find() method in JPA API and return exactly what they are doing there.

    /**
     * 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);

You see here in find, which I think is similar to your getCustomer() method, it will return null if none is found, and only throwing IllegalArgumentException if the argument is invalid.

If the find() method is not close to what you want with getCustomer() you should implement the same behavior as 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();

Which will throw EntityNotFoundException if no result is found, NonUniqueResultException if multiple instances are found or IllegalStateException if the SQL is wrong.

You have to decide which behavior is most suitable for you.

The same goes for 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() will return null if none is found and only throwing exception if the SQL is illegal.

By following this behaviour, you are being consistent, and your users will get a feeling of knowing how the library is.


An alternate behavior is to return an empty collection instead of null. This is how Google Guava have implemented their API, and which is really the preferred why. However, I like consistency, and still think you should implement the library as close to the standard as possible.


Resources

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

梦过后 2024-10-23 00:40:25
  1. 无效的。但是方法 getCustomer() 应该返回 Customer。如果它返回 String,则可能应该调用 getCustomerName()getCustomerId()
  2. 空列表
  3. 抛出异常。可能用应用程序层异常包装它。
  1. null. But method getCustomer() should return Customer. If it returns String it should be probably called getCustomerName() or getCustomerId()
  2. empty list
  3. throw exception. Probably wrap it with application-layer exception.
抱猫软卧 2024-10-23 00:40:25

示例 1:由于未检索到任何内容,因此应返回 null。或者,可以选择空对象模式

示例 2:优先选择空 ArrayList 而不是 null。请参阅“Effective Java”第 43 条:返回空数组或集合,而不是 null

示例 3:将 SQLException 转换为更高级别的 Exception 并抛出它。请参阅“Effective Java”第 61 条:抛出适合抽象的异常

Example 1: Since nothing is retrieved, null should be returned. Alternatively, Null-Object pattern can be a choice.

Example 2: Prefer empty ArrayList to null. See "Effective Java" Item 43: Return empty arrays or collections, not nulls

Example 3: Translate the SQLException to higher Exception and throw it. See "Effective Java" Item 61: Throw exceptions appropriate to the abstract

溺ぐ爱和你が 2024-10-23 00:40:25

由于它是您的 API,因此只要保持一致并确保正确记录它,任何方法都是好的。

对于 1 & 2:
但请注意,返回空值将强制客户端代码继续执行如下检查:

result = yourAPICall();
if(result != null){
   // do something
}

这就是为什么我更喜欢返回空对象或集合

For 3:
这将取决于您的 API 设计。但首先,永远不要在调用堆栈中抛出低级异常。您应该将它们包装在为您的 API 设计的自定义异常类中,以便您的客户端代码只需要捕获您的 API 异常,而不是各种较低级别的异常(SQLException、IOException 等...)

其次,您必须决定是否存在首先抛出异常有什么好处。抛出异常使客户端代码能够自定义处理其 API 依赖项遇到的问题的方式。但抛出它也会阻止您作为 API 设计者设计内部意外情况,从而使您的代码可能从问题中恢复(使您的 API 不太健壮)

Since it's your API, any approach is good as long as you are consistent and make sure that it is documented properly.

For 1 & 2:
Just take note though, that returning nulls will force client code to keep on performing checks like the following:

result = yourAPICall();
if(result != null){
   // do something
}

Which is why I prefer returning empty objects or collections

For 3:
That will depend on your APIs design. But first, never throw low level exceptions up the call stack. You should wrap them in an custom exception class designed for your API so that your client code will only need to catch your API exceptions rather than a variety of lower level ones (SQLException, IOException etc...)

Second, you must decide if there is any benefit for the exception to be thrown in the first place. Throwing an exception allows client code the ability to customize how it wants to the handle problems encountered by its API dependencies. But throwing it also prohibits you as the API designer from designing internal contingencies that will allow your code to perhaps recover from the problem (makes your API less robust)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文