0

I have a simple User class and its properties are annotated with both @NotBland and lombok @NonNull.

@AllArgsConstructor
@Data
@Builder
public class User {

    @NonNull
    private String name;

    @NonNull
    private String id;

    @NotBlank
    private String address;
}

What i am expecting from this is when i try to set blank in address field it informs me at compile time or at least crash at runtime. Lombok @NonNull is working in that way and is raising NPEs at runtime.

I wrote the following test to check this

@Test
public void user_null_test(){

    User user = User.builder()
            .id("")
            .name("")
            .address("")
            .build();



    assertThat(user).isNotNull();

But the user is a valid user object with address being empty. Obviously i can use the following code to check for validation in my test

    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();

    Set<ConstraintViolation<User>> violations = validator.validate(user);
    assertThat(violations).isEmpty(); 

but i can't do that or want to write this type of code in my actual code base. So my question is what is the use of @NotBlank if it does not raise any error at compile or run time if we are setting a property to as empty string when it is not supposed to be so according to the set annotation.

Manza
  • 3,427
  • 4
  • 36
  • 57
Madu
  • 4,849
  • 9
  • 44
  • 78
  • 1
    Because validation doesn't work that way. Comparing Lombok with Javax.validation is comparing apples and oranges and find it strange that both differ from bananas. Lombok will generate code in your setter/constructor activly validating that. The `@NonBlank` requires a validator to check your object. It doesn't do any checks at compile time (also would that really help in someone subitting an empty HTML form?). So only at runtime when activly avalidated it will throw this error. – M. Deinum Jan 11 '21 at 10:09
  • So do you mean that at run time if someone is trying to set the address field to empty string it will give an error? – Madu Jan 11 '21 at 10:25
  • No, it will only give an error if **explicitly** validated. – M. Deinum Jan 11 '21 at 10:33
  • So whats the use of this then, in which case it will give caution that some thing is not been set according to standards defined? – Madu Jan 14 '21 at 00:04
  • It is a standardized validation api it doesn't do anything for code generation. Annotations by themselves are nothing just meta-data you need something (an implementation) to do something. So either you need a code generator for those annotations, generating butecode doing the validation or something at runtime. Only the latter is available afaik. – M. Deinum Jan 14 '21 at 07:02

0 Answers0