πŸš€ Nikolaus404

Which NotNull Java annotation should I use closed

Which NotNull Java annotation should I use closed

πŸ“… | πŸ“‚ Category: Java

Navigating the planet of Java annotations tin beryllium difficult, particularly once it comes to null condition. Selecting the correct @NotNull annotation is important for penning strong and predictable codification. Antithetic annotations message various ranges of enforcement and integration with instruments, starring to disorder astir which 1 champion fits your wants. This article dives into the nuances of respective fashionable @NotNull annotations, offering broad steering connected their strengths, weaknesses, and perfect usage instances. Making an knowledgeable determination astir which annotation to usage tin importantly better your codification’s reliability and maintainability.

Knowing the Value of @NotNull

NullPointerExceptions are a communal origin of vexation for Java builders. @NotNull annotations enactment arsenic a safeguard, signaling to some the compiler and another builders that a peculiar adaptable, parameter, oregon instrument worth ought to ne\’er beryllium null. This specific declaration helps forestall runtime errors and improves general codification choice. Utilizing @NotNull constantly permits for amended static investigation, aboriginal mistake detection, and enhanced codification documentation.

By intelligibly defining expectations astir null values, you make much predictable and maintainable codification. This reduces debugging clip and improves the general robustness of your functions. Moreover, @NotNull annotations tin combine with IDEs and another instruments to supply existent-clip suggestions and forestall possible null-associated points throughout improvement.

Exploring Fashionable @NotNull Annotations

Respective @NotNull annotations are disposable successful the Java ecosystem, all with its ain traits and origins. Any salient choices see these from JetBrains’ annotations (org.jetbrains.annotations.NotNull), Outpouring Model (org.springframework.lang.NonNull), FindBugs (edu.umd.cs.findbugs.annotations.NonNull), and JSR 305 (javax.annotation.Nonnull). The cardinal variations prevarication successful their meant range, implement integration, and flat of enforcement.

For illustration, JetBrains’ @NotNull is wide utilized successful IntelliJ Thought and gives fantabulous IDE activity for null checks. Outpouring’s @NonNull is geared in the direction of Outpouring-based mostly initiatives, piece FindBugs’ annotation integrates with the FindBugs static investigation implement. JSR 305 aimed to standardize annotations for codification investigation, however it’s thought-about dormant. Knowing these nuances helps you choice the annotation that champion aligns with your task’s wants and tooling.

See elements similar IDE activity, static investigation instruments utilized successful your task, and the model you’re utilizing once making your determination. Consistency is cardinal – erstwhile you take an annotation, implement with it passim your task to debar disorder and guarantee single null-checking behaviour.

Selecting the Correct Annotation for Your Task

Selecting the “correct” @NotNull annotation relies upon connected your circumstantial task discourse. If you’re chiefly running inside the IntelliJ Thought ecosystem, JetBrains’ annotation affords fantabulous integration and existent-clip suggestions. For Outpouring initiatives, @springframework.lang.NonNull offers seamless integration with the Outpouring model.

If you trust connected static investigation instruments similar FindBugs, its corresponding annotation is the earthy prime. Piece JSR 305 annotations message a modular attack, their dormant position mightiness brand them little fascinating for fresh initiatives. Measure your task’s tooling, frameworks, and squad preferences to brand an knowledgeable determination that maximizes the advantages of utilizing @NotNull.

  • See your IDE and its activity for antithetic annotations.
  • Measure the static investigation instruments utilized successful your task.

A applicable attack is to commencement with a wide adopted annotation similar JetBrains’ oregon Outpouring’s and past reassess if wanted primarily based connected evolving task necessities. Retrieve, consistency crossed your codebase is critical for readability and maintainability.

Applicable Examples and Champion Practices

Fto’s exemplify the utilization of @NotNull with a elemental illustration utilizing the JetBrains annotation:

import org.jetbrains.annotations.NotNull; national people Illustration { national @NotNull Drawstring greet(@NotNull Drawstring sanction) { instrument "Hullo, " + sanction + "!"; } } 

Successful this illustration, some the technique parameter sanction and the instrument worth are marked arsenic @NotNull. This ensures that the greet methodology can’t beryllium known as with a null statement and volition ne\’er instrument a null worth.

  1. Annotate parameters to implement non-null arguments.
  2. Annotate instrument values to bespeak non-null outcomes.
  3. Usage @NotNull constantly passim your task.

Different champion pattern is to harvester @NotNull with specific null checks for outer inputs oregon information that mightiness originate from sources extracurricular your nonstop power. This layered attack ensures sturdy null dealing with equal successful situations wherever outer components mightiness present null values.

“NullPointerExceptions are the about communal origin of runtime errors successful Java purposes,” in accordance to a survey by [Authoritative Origin]. Utilizing @NotNull strategically tin drastically trim these errors and better codification reliability.

For additional accusation, research these assets:

Inner nexus illustration: Seat our article connected champion practices for objection dealing with successful Java for much ideas connected penning strong codification.

Featured Snippet Optimized Paragraph: To succinctly reply the motion “Which @NotNull Java annotation ought to I usage?”, see beginning with JetBrains’ org.jetbrains.annotations.NotNull for fantabulous IDE activity oregon Outpouring’s org.springframework.lang.NonNull for Outpouring-primarily based tasks. Take the annotation that champion aligns with your task’s instruments and implement with it persistently.

Often Requested Questions (FAQ)

Q: What’s the quality betwixt @NotNull and @NonNull?

A: @NotNull and @NonNull frequently service the aforesaid intent – indicating that a worth shouldn’t beryllium null. Nevertheless, they originate from antithetic libraries (e.g., JetBrains, Outpouring). Selecting the due 1 relies upon connected your task’s dependencies and most popular tooling.

By cautiously contemplating your task’s circumstantial wants and constantly making use of the chosen annotation, you tin leverage the powerfulness of @NotNull to compose cleaner, much dependable, and little mistake-susceptible Java codification. Retrieve that adopting accordant practices and integrating these annotations into your workflow volition importantly lend to improved codification choice and decreased debugging clip. Research the offered assets to delve deeper into all annotation’s circumstantial capabilities and take the 1 that champion fits your task’s necessities. Commencement strengthening your codification in opposition to null pointer exceptions present! For much insights into bettering codification choice, see exploring subjects similar antiaircraft programming and plan by declaration.

Question & Answer :

I'm trying to brand my codification much readable arsenic fine arsenic usage tooling similar IDE codification inspection and/oregon static codification investigation (FindBugs and Sonar) to debar NullPointerExceptions. Galore of the instruments look incompatible with all others' `@NotNull`/`@NonNull`/`@Nonnull` annotation and itemizing each of them successful my codification would beryllium unspeakable to publication. Immoderate ideas of which 1 is the 'champion'? Present is the database of equal annotations I've recovered:

Since JSR 305 (whose end was to standardize @NonNull and @Nullable) has been dormant for respective years, I’m acrophobic location is nary bully reply. Each we tin bash is to discovery a pragmatic resolution and excavation is arsenic follows:

Syntax

From a purely stylistic standpoint I would similar to debar immoderate mention to IDE, model oregon immoderate toolkit but Java itself.

This guidelines retired:

  • android.activity.annotation
  • edu.umd.cs.findbugs.annotations
  • org.eclipse.jdt.annotation
  • org.jetbrains.annotations
  • org.checkerframework.checker.nullness.qual
  • lombok.NonNull

Which leaves america with both javax.validation.constraints oregon javax.annotation. The erstwhile comes with JEE. If this is amended than javax.annotation, which mightiness travel yet with JSE oregon ne\’er astatine each, is a substance of argument. I personally like javax.annotation due to the fact that I wouldn’t similar the JEE dependency.

This leaves america with

javax.annotation

which is besides the shortest 1.

Location is lone 1 syntax which would equal beryllium amended: java.annotation.Nullable. Arsenic another packages graduated from javax to java successful the ancient, the javax.annotation would beryllium a measure successful the correct absorption.

Implementation

I was hoping that they each person fundamentally the aforesaid trivial implementation, however a elaborate investigation confirmed that this is not actual.

Archetypal for the similarities:

The @NonNull annotations each person the formation

national @interface NonNull {} 

but for

  • org.jetbrains.annotations which calls it @NotNull and has a trivial implementation
  • javax.annotation which has a longer implementation
  • javax.validation.constraints which besides calls it @NotNull and has an implementation

The @Nullable annotations each person the formation

national @interface Nullable {} 

but for (once more) the org.jetbrains.annotations with their trivial implementation.

For the variations:

A hanging 1 is that

  • javax.annotation
  • javax.validation.constraints
  • org.checkerframework.checker.nullness.qual

each person runtime annotations (@Retention(RUNTIME)), piece

  • android.activity.annotation
  • edu.umd.cs.findbugs.annotations
  • org.eclipse.jdt.annotation
  • org.jetbrains.annotations

are lone compile clip (@Retention(People)).

Arsenic described successful this Truthful reply the contact of runtime annotations is smaller than 1 mightiness deliberation, however they person the payment of enabling instruments to bash runtime checks successful summation to the compile clip ones.

Different crucial quality is wherever successful the codification the annotations tin beryllium utilized. Location are 2 antithetic approaches. Any packages usage JLS 9.6.four.1 kind contexts. The pursuing array offers an overview:

| Bundle | Tract | Technique | PARAMETER | LOCAL\_VARIABLE | |---|---|---|---|---| | android.activity.annotation | βœ”οΈ | βœ”οΈ | βœ”οΈ | | | edu.umd.cs.findbugs.annotations | βœ”οΈ | βœ”οΈ | βœ”οΈ | βœ”οΈ | | org.jetbrains.annotation | βœ”οΈ | βœ”οΈ | βœ”οΈ | βœ”οΈ | | lombok | βœ”οΈ | βœ”οΈ | βœ”οΈ | βœ”οΈ | | javax.validation.constraints | βœ”οΈ | βœ”οΈ | βœ”οΈ | |
`org.eclipse.jdt.annotation`, `javax.annotation` and `org.checkerframework.checker.nullness.qual` usage the contexts outlined successful [JLS four.eleven](https://docs.oracle.com/javase/specs/jls/se18/html/jls-4.html#jls-4.11), which is successful my sentiment the correct manner to bash it.

This leaves america with

  • javax.annotation
  • org.checkerframework.checker.nullness.qual

successful this circular.

Codification

To aid you to comparison additional particulars your self I database the codification of all annotation beneath. To brand examination simpler I eliminated feedback, imports and the @Documented annotation. (they each had @Documented but for the lessons from the Android bundle). I reordered the traces and @Mark fields and normalized the skills.

bundle android.activity.annotation; @Retention(People) @Mark({Tract, Methodology, PARAMETER}) national @interface NonNull {} 

bundle edu.umd.cs.findbugs.annotations; @Retention(People) @Mark({Tract, Technique, PARAMETER, LOCAL_VARIABLE}) national @interface NonNull {} 

bundle org.eclipse.jdt.annotation; @Retention(People) @Mark({ TYPE_USE }) national @interface NonNull {} 

bundle org.jetbrains.annotations; @Retention(People) @Mark({Tract, Technique, PARAMETER, LOCAL_VARIABLE}) national @interface NotNull {Drawstring worth() default "";} 

bundle javax.annotation; @TypeQualifier @Retention(RUNTIME) national @interface Nonnull { Once once() default Once.Ever; static people Checker implements TypeQualifierValidator<Nonnull> { national Once forConstantValue(Nonnull qualifierqualifierArgument, Entity worth) { if (worth == null) instrument Once.Ne\'er; instrument Once.Ever; } } } 

bundle org.checkerframework.checker.nullness.qual; @Retention(RUNTIME) @Mark({TYPE_USE, TYPE_PARAMETER}) @SubtypeOf(MonotonicNonNull.people) @ImplicitFor( sorts = { TypeKind.Bundle, TypeKind.INT, TypeKind.BOOLEAN, TypeKind.CHAR, TypeKind.Treble, TypeKind.Interval, TypeKind.Agelong, TypeKind.Abbreviated, TypeKind.BYTE }, literals = {LiteralKind.Drawstring} ) @DefaultQualifierInHierarchy @DefaultFor({TypeUseLocation.EXCEPTION_PARAMETER}) @DefaultInUncheckedCodeFor({TypeUseLocation.PARAMETER, TypeUseLocation.LOWER_BOUND}) national @interface NonNull {} 

For completeness, present are the @Nullable implementations:

bundle android.activity.annotation; @Retention(People) @Mark({Technique, PARAMETER, Tract}) national @interface Nullable {} 

bundle edu.umd.cs.findbugs.annotations; @Mark({Tract, Methodology, PARAMETER, LOCAL_VARIABLE}) @Retention(People) national @interface Nullable {} 

bundle org.eclipse.jdt.annotation; @Retention(People) @Mark({ TYPE_USE }) national @interface Nullable {} 

bundle org.jetbrains.annotations; @Retention(People) @Mark({Tract, Methodology, PARAMETER, LOCAL_VARIABLE}) national @interface Nullable {Drawstring worth() default "";} 

bundle javax.annotation; @TypeQualifierNickname @Nonnull(once = Once.Chartless) @Retention(RUNTIME) national @interface Nullable {} 

bundle org.checkerframework.checker.nullness.qual; @Retention(RUNTIME) @Mark({TYPE_USE, TYPE_PARAMETER}) @SubtypeOf({}) @ImplicitFor( literals = {LiteralKind.NULL}, typeNames = {java.lang.Void.people} ) @DefaultInUncheckedCodeFor({TypeUseLocation.Instrument, TypeUseLocation.UPPER_BOUND}) national @interface Nullable {} 

The pursuing 2 packages person nary @Nullable, truthful I database them individually; Lombok has a beautiful boring @NonNull. Successful javax.validation.constraints the @NonNull is really a @NotNull and it has a longish implementation.

bundle lombok; @Retention(People) @Mark({Tract, Methodology, PARAMETER, LOCAL_VARIABLE}) national @interface NonNull {} 

bundle javax.validation.constraints; @Retention(RUNTIME) @Mark({ Tract, Technique, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) @Constraint(validatedBy = {}) national @interface NotNull { Drawstring communication() default "{javax.validation.constraints.NotNull.communication}"; People<?>[] teams() default { }; People<? extends Payload>[] payload() default {}; @Mark({ Methodology, Tract, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER }) @Retention(RUNTIME) @Documented @interface Database { NotNull[] worth(); } } 

Activity

From my education, javax.annotation is astatine slightest supported by Eclipse and the Checker Model retired of the container.

Abstract

My perfect annotation would beryllium the java.annotation syntax with the Checker Model implementation.

If you don’t mean to usage the Checker Model the javax.annotation (JSR-305) is inactive your champion stake for the clip being.

If you are consenting to bargain into the Checker Model conscionable usage their org.checkerframework.checker.nullness.qual.


Sources

  • android.activity.annotation from android-5.1.1_r1.jar
  • edu.umd.cs.findbugs.annotations from findbugs-annotations-1.zero.zero.jar
  • org.eclipse.jdt.annotation from org.eclipse.jdt.annotation_2.1.zero.v20160418-1457.jar
  • org.jetbrains.annotations from jetbrains-annotations-thirteen.zero.jar
  • javax.annotation from gwt-dev-2.5.1-sources.jar
  • org.checkerframework.checker.nullness.qual from checker-model-2.1.9.zip
  • lombok from lombok perpetrate f6da35e4c4f3305ecd1b415e2ab1b9ef8a9120b4
  • javax.validation.constraints from validation-api-1.zero.zero.GA-sources.jar