Given a definition like the following

public interface Type
{
    public static final Type NULL = new Type() { public void method() {} };

    public void method();
}

is there any case of an equality check error if all code that creates objects from implementations of Type, uses (and checks for equality) the Type.NULL value mentioned above?

For example, assuming declarations like

public Type calculate() {...}
Type t = calculate();

the return value of calculate() could be Type.NULL whenever null is the result and instead of checking

if (t == null)

one would check

if (t == Type.NULL)

thus making the return type of calculate() always non-null.

(The question is not about whether this is the best practice to follow, it just tries to verify that there can not be any accuracy issues with this approach.)

有帮助吗?

解决方案

From the point of view of OO design, I would distinguish between two situations.

  1. You want to model that nothing has been returned, the variable has not defined value. In this case I would use null. I cannot see any advantage of using if (t == Type.NULL) instead of if (t == null).

  2. You want to model an empty operation/value has been returned, the variable is defined, but the value is a kind of a "zero". In that case I would use your solution, but I would not call it NULL, but rather VOID or EMPTY or similar based on your business logic. This is preferable not because you want to use if (t == Type.NULL) instead of if (t == null), but because you want to not use any if at all - you may just use the variable as it contains a meaningful (however empty) value.

其他提示

Another option is to create a concrete NullType subclass of type:

class NullType extends Type {
    @Override
    public void method() {
        ...
    }
}

Then your method can return a NullType instance, so the check would be:

if (t instanceof NullType)

It might make sense to have NullType be a singleton as well.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top