1

I've been working on a project which has been developed by other developers. In this project, any method that returns an entity or object is designed to return a special value called EMPTY_VALUE.

public Customer getCustomer() {
    if (everythingFine) {
        return realCustomer();
    } else {
        Customer.EMPTY_VALUE;
    }
}

And the Customer class:

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

    private String firstName;
    private STring lastName;

    public Customer() {
        this.firstName = "";
        this.lastName = "";
    }
}

In other places that use the getCustomer() method:

Customer customer = getCustomer();
if (customer != Customer.EMPTY_VALUE) {
    doSomething(customer);
}

Does the above way has any advantages over the null-checking? Does it buy us anything?

Customer customer = getCustomer();
if (customer != null) {
    doSomething(customer);
}
4

3 回答 3

4

This is an example of the Null Object Pattern. The advantage is that you can remove explicit null checks by instead just using an object that does a default behavior. In this case, the null object returns empty strings when its fields are queried, so if that's what you want in the case of no result anyway, you just saved yourself a check for null. Obviously like all design patterns, its usefulness depends on the particular situation.

于 2012-07-01T01:28:55.100 回答
4

I would say neither. Don't return null or a return special "error-object" from a method. Let them throw an exception instead. That way you don't need to "check" every time you you call it.

public Customer getCustomer() {

    if (everythingFine) {
        return realCustomer();

    throw new NoCustomerException();
}

And the code using the method would be a lot simpler:

doSomething(getCustomer());

It could be (like the example above) an runtime exception or a checked exception.


If you have to choose between the two I would choose the non-null variant, just like I would choose to return an empty list from a method instead of null. I would however urge you not to write any special code to handle that special object, it should be handled like any other customer.

于 2012-07-01T01:29:45.047 回答
4

我不喜欢创建一个虚拟的空客户对象的想法。它的语义是什么?是不是真正的客户?

在这种情况下,我更愿意使用来自 Guava 的Optionalnull之类的东西,或者可能只是根据客户端代码使用。阅读链接中的描述以查看常见用途和可选的 API。

于 2012-07-01T01:36:11.260 回答