user8371723
user8371723

Reputation:

@NotNull javax annotation vs Intellij @NotNull annotation

Which of these annotations should i use? INTELLIJ introduced own library with annotations. I read that it is good practive to mark methods parameters and class attrbiutes with these annotations but i wonder what they do. There are many libraries with annotations(spring also have annotations like Nullable). Javax annotations are implemented by hibernate validator which validates particular classes but INTELLIJ annotations only remid or warn about method's attribute. Lets say that i have class with Intellij annotations

public class XYZ{
@NotNull
private int id;
@Nullable
private String z;
@NotNull
private String y;

} and

public void method(@NotNull String a,String b)
{
...
}

All annotations are chekced during runtime, what would do Intellij if @NotNull parameter will be null? It doesnt throw any error or somethind like that, only warn me, why it can be useful for me ? I think that it might be more useful for someone who will try read my code.

The other example when i have ManyToMany relation in my user then should i mark it as @Nullable ? It will be every time null when i created new user so it isnt necessary, is it?

Upvotes: 9

Views: 5960

Answers (1)

albert_nil
albert_nil

Reputation: 1658

i believe you are mixing things:

  1. intellij annotations are to help the developer on spotting probable bugs. If you say that a parameter is Nullable for example, it will warn you if you are not protecting your code against NullPointerExceptions. This can be done compile-time (not related to runtime).
  2. javax validation annotations instead, are about adding validations to fields and throw errors if not met. it's about your business, not about bugs in your code; there might be no bug at all. For example, they can be used to verify that external input matches a specific criteria. Let's suppose you implement an API in your application to be called from the outside. If you add NotNull annotation to a field, if the API caller does not set that field, it will receive an error. Your application is perfectly fine, no bug at all. Obviously, these validations are about the data and done on runtime.

Upvotes: 9

Related Questions