What is point of constraint validation @Null?

旧街凉风 提交于 2019-12-10 01:30:19

问题


I was checking list of available constraints in javax.validation package and I noticed that there is an annotation @Null which force the field to be null.

I do not understand what is point of adding it to my field if I already know it should be null.

For example look at this class:

public class MyClass{

    @NotNull
    private String myString1;

    @Null
    private String myString2;

    // getter setters...
}

@NotNull completely makes sense. I do not expect myString1 to be null. but @Null makes myString2 useless. What is point of having a field which should always be null.


回答1:


You may want to use @Null in combination with "Validation Group" to validate the null constraint only in certain cases.

Good explanation and example on validation groups provided by Hibernate

You will define validation group as simple interface

public interface FirstSave {}

then use it in constraint

public class MyClass {

    @Null(groups = FirstSave.class)
    private LocalDate lastUpdate;
}

then if lastUpdate is not null, calling validator.validate(myClassInstance) will not produce constraint violation (Default group was used), but calling validator.validate(myClassInstance, FirstSave.class) will.

You also have the possibility to provide your own implementation on how to use the annotation, i.e. I've seen validation method being annotated with @Null where null returned by the method meant that everything is alright. In the background there was probably custom implementation on what to do if annotated method returned not null result, but I didn't go deep into the code...




回答2:


Quoting from this documentation, here is the requirement of the null annotation.

At first sight using null annotations for API specifications in the vein of Design by Contract only means that the signatures of all API methods should be fully annotated, i.e., except for primitive types like int each parameter and each method return type should be marked as either @NonNull or @Nullable. Since this would mean to insert very many null annotations, it is good to know that in well-designed code (especially API methods), @NonNull is significantly more frequent than @Nullable. Thus the number of annotations can be reduced by declaring @NonNull as the default, using a @NonNullByDefault annotation at the package level.

However, having said that, yes you are right, @Null does not make much sense and in a proper well designed code, @NotNull is of much more importance and much more frequent. @Null or @Nullable exists just to denote that null values are to be expected here and helps prevent redundant checking of null values by both the caller and the callee. Hope this helps.



来源:https://stackoverflow.com/questions/44683296/what-is-point-of-constraint-validation-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!