java api 设计 - NULL 或异常 [英] java api design - NULL or Exception

查看:39
本文介绍了java api 设计 - NULL 或异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

返回空值还是从 API 方法中抛出异常更好?

Is it better to return a null value or throw an exception from an API method?

返回空值需要进行丑陋的空值检查,如果不检查返回值会导致重大质量问题.

Returning a null requires ugly null checks all over, and cause a major quality problem if the return is not checked.

抛出异常会强制用户针对错误条件进行编码,但由于 Java 异常会冒泡并强制调用者代码处理它们,因此通常使用自定义异常可能是一个坏主意(特别是在 Java 中).

Throwing an exception forces the user to code for the faulty condition, but since Java exceptions bubble up and force the caller code to handle them, in general, using custom exceptions may be a bad idea (specifically in java).

有什么合理而实用的建议吗?

Any sound and practical advice?

推荐答案

我认为答案完全取决于您的应用程序的上下文,以及您认为是特殊情况"还是程序员错误.

I think the answer is entirely dependent on the context of your application, and what you consider to be an "exceptional circumstance" versus programmer error.

例如,如果编写 XML 解析器,您可以选择实现如下方法:

For example, if writing an XML parser you may choose to implement methods like:

/**
 * Returns first child element with matching element name or else
 * throws an exception.  Will never return null.
 */
Element getMandatoryChildElement(Element parent, String elementName)
throws MissingElementException;

... 因为这种方法允许您在单个逻辑块中实现消息解析代码,而无需在检索每个元素或属性后检查消息是否格式正确.

... as this approach allows you to implement your message parsing code in a single block of logic, without having to check that the message is well-formed after retrieving each element or attribute.

这篇关于java api 设计 - NULL 或异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆