5

I'm wanting to know where exactly the comment should go and what keyword I should use as I cant really seem to find an example online, should I for example do this?

/**
 * @invariant invariant example
 */
 public class Example {
 } 
Bartosz Bilicki
  • 12,599
  • 13
  • 71
  • 113
Moulie415
  • 317
  • 3
  • 13

1 Answers1

4

There are a few possibilites

@Contract annotations

Some examples

  • @Contract("_, null -> null") - method returns null if its second argument is null.

  • @Contract("_, null -> null; _, !null -> !null") - method returns null if its second argument is null, and not-null otherwise.

  • @Contract("true -> fail") - a typical assertFalse() method which throws an exception if true is passed to it.

See https://www.jetbrains.com/help/idea/2016.2/contract-annotations.html for more details.

You could use them without IntelliJ IDEA. IDEA just has smart support for those annotations. It will check your method code if specified invariants are really met.

Textual description

This method does not cover all cases. For more complex dependencies between fields you need to describe invariant using english words.

For example, https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#put(K,%20V)

If the map previously contained a mapping for the key, the old value is replaced by the specified value.

Exceptions

Also, exceptions can be used to describe and enforce invariant. For above-mentioned Map.put method we have following exceptions for invalid arguments (arguments that would break class invariant)

  • @throws UnsupportedOperationException if the put operation is not supported by this map
    • @throws ClassCastException if the class of the specified key or value prevents it from being stored in this map
    • @throws NullPointerException if the specified key or value is null and this map does not permit null keys or values
    • @throws IllegalArgumentException if some property of the specified key or value prevents it from being stored in this map
Bartosz Bilicki
  • 12,599
  • 13
  • 71
  • 113