Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JetBrains' @Contract annotation

How does the org.jetbrains.annotations.Contract annotation work? How does IntelliJ IDEA support it?

like image 550
Atom 12 Avatar asked Jan 05 '16 20:01

Atom 12


People also ask

What is org Jetbrains annotations NotNull?

The @NotNull annotation is, actually, an explicit contract declaring that: A method should not return null. Variables (fields, local variables, and parameters) cannot hold a null value.

How do I change a contract method?

Press Alt+Enter on a method, and select Add method contract or Edit method contract. Configure the contract and apply the changes.

How do I see annotations in Intellij?

Enable annotationsRight-click the gutter in the editor or in the Differences Viewer and select Annotate with Git Blame from the context menu. You can assign a custom shortcut to the Annotate command: go to the Keymap page of the IDE settings Ctrl+Alt+S and look for Version Control Systems | Git | Annotate.


1 Answers

First off, I should say that this annotation is only for IDEA to use to check for possible errors. The Java compiler will ignore it almost entirely (it'll be in the compiled artifact but have no effect). Having said that...

The goal of the annotation is to describe a contract that the method will obey, which helps IDEA catch problems in methods that may call this method. The contract in question is a set of semi-colon separated clauses, each of which describes an input and an output that is guaranteed to happen. Cause and effect are separated by ->, and describe the case that when you provide X to the method, Y will always result. The input is described as a comma-separated list, describing the case of multiple inputs.

Possible inputs are _ (any value), null, !null (not-null), false and true, and possible outputs adds fail to this list.

So for example, null -> false means that, provided a null input, a false boolean is the result. null -> false; !null -> true expands on this to say that null will always return false and a non-null value will always return true, etc. Finally, null -> fail means the method will throw an exception if you pass it a null value.

For a multiple-argument example, null, !null -> fail means that, in a two-argument method, if the first argument is null and the second is not null, an exception will be thrown, guaranteed.

If the method does not change the state of the object, but just returns a new value, then you should set pure to true.

like image 147
dcsohl Avatar answered Sep 28 '22 08:09

dcsohl