Frage

I was looking at Guava's Optional class and its justification, and I wondered whether a similar class to fail-fast when representing values that must not be null would be helpful. I can't find any discussion of this idea so I thought I'd ask here.

My first attempt would try to stay in the style used by Guava, a Mandatory<T>, exposing a static factory of(T t). This method throws NullPointerException if called with a null argument.

My particular interest is nailing down the semantics of interface methods in respect of null handling. I think that whether to accept null arguments or not is a design decision that should be specifiable in the interface so that client code can be designed accordingly and can avoid duplicating precondition checking logic. As such, an interface using this class might have methods like

fire(Mandatory<Employee> employee);

and a client might call

fire(Mandatory.of(unfortunateEmployee));

I suspect that the Mandatory type would be quite easy to find using aspects and the like to hook in further checks before invocation if it was absolutely vital that such marked method arguments should not be null.

I've also considered annotation-based approaches such as fire(@NotNull Employee employee) but the implementations I've seen require additional wiring up of validators.

So, the questions... does this idea exist anywhere already? If not, have I missed something obvious that undermines it? Or a better idea to achieve this?

War es hilfreich?

Lösung

fire(Mandatory<Employee> employee);

If you had a method with this signature, you could still call fire(null); it'd just be that you'd have a null of type Mandatory<Employee> instead of type Employee. You haven't actually improved safety at all; you've just added a redundant layer of wrapping.

If you want to enforce that a parameter is required, good practice is to use e.g. Preconditions.checkNotNull as the first thing in your method to immediately throw a NullPointerException if the value is null.

Andere Tipps

adding a Mandatory.of method that throws NPE

Using your T variable will already throw a NullPointerException, so what's the point?

How to specify that a parameter is required as part of the contract?

Javadoc has been used for this for a long time.

Yeah, but I want to enforce it.

You have too much time on your hands. That aside...

@NotNull is the "new way". You can use AOP to wire not-null validation automatically for the desired methods. Here are a couple of great implementations:

http://blog.solidcraft.eu/2010/09/getting-rid-of-null-parameters-with.html http://janistoolbox.typepad.com/blog/2009/12/aopvalidationnotnull.html

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top