Devuelve una estructura de datos vacía (entidad) en lugar de nulo, ¿es bueno?

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);
}

preguntado el 01 de julio de 12 a las 02:07

3 Respuestas

Este es un ejemplo de Patrón de objeto nulo. 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.

Respondido 01 Jul 12, 02:07

I don't like the idea of creating a dummy empty Customer object. What are the semantics of it? Is it a real Customer or not?

I would prefer to use something like Opcional from Guava in this situation or might just use null depending on the client code. Read the description in the link to see common uses and the API for Optional.

Respondido 01 Jul 12, 02:07

yo diría ninguno. 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.


Si vous a-tener 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.

Respondido 01 Jul 12, 10:07

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.