返回空数据结构(实体)而不是null,是不是很好?

Gen*_*zer 1 java entity

我一直致力于一个由其他开发人员开发的项目.在此项目中,任何返回实体或对象的方法都旨在返回一个名为的特殊值EMPTY_VALUE.

public Customer getCustomer() {
    if (everythingFine) {
        return realCustomer();
    } else {
        Customer.EMPTY_VALUE;
    }
}
Run Code Online (Sandbox Code Playgroud)

而Customer类:

public class Customer {
    public static final Customer EMPTY_VALUE = new Customer();

    private String firstName;
    private STring lastName;

    public Customer() {
        this.firstName = "";
        this.lastName = "";
    }
}
Run Code Online (Sandbox Code Playgroud)

在其他使用getCustomer()方法的地方:

Customer customer = getCustomer();
if (customer != Customer.EMPTY_VALUE) {
    doSomething(customer);
}
Run Code Online (Sandbox Code Playgroud)

上述方法是否比null-checking 有任何优势?它给我们买了什么吗?

Customer customer = getCustomer();
if (customer != null) {
    doSomething(customer);
}
Run Code Online (Sandbox Code Playgroud)

dac*_*cwe 5

我会说没有.不要null从方法返回或返回特殊的"错误对象".让他们抛出异常.这样,每次调用它时都不需要"检查".

public Customer getCustomer() {

    if (everythingFine) {
        return realCustomer();

    throw new NoCustomerException();
}
Run Code Online (Sandbox Code Playgroud)

使用该方法的代码会简单得多:

doSomething(getCustomer());
Run Code Online (Sandbox Code Playgroud)

它可能(如上例所示)运行时异常或已检查异常.


如果你必须在两者之间做出选择,我会选择非null变体,就像我选择从方法中返回一个空列表而不是null.但是,我会建议您不要编写任何特殊代码来处理该特殊对象,它应该像任何其他客户一样处理.