Renato
Renato

Reputation: 13690

How to get IntelliJ to warn about unsafe usages of Optional.get()

Some not-so-careful colleagues of mine have been passing around Optional instances and assuming it's safe to call get on them without calling isPresent first.

I know... this shouldn't happen, but the type-system won't stop them!!

So, I wanted IntelliJ to do it. Is it possible to configure IntelliJ so that it will warn (or even throw a compiling error) about calling Optional.get() without first calling Optional.isPresent()?

Upvotes: 8

Views: 1002

Answers (2)

Renato
Renato

Reputation: 13690

IntelliJ 2016.1 supports this out-of-the-box!

By default, calling get() without verifying with isPresent() first will issue a warning, but you can go to the "Inspections" screen and set Optiong.get() without isPresent() check to have severity "Error" if you prefer.

Upvotes: 3

SlopeOak
SlopeOak

Reputation: 175

You could use an inspection to flag instances and show you a warning/error. This may be exclusive to ultimate.

To add a custom inspection, follow https://www.jetbrains.com/idea/help/creating-custom-inspections.html, or do this:

  1. Open the settings (CTRL+ALT+S) and search for Inspections.
  2. In the tree, find "General" and under that, "Structural Search Inspection".
  3. Under the description you'll see a severity/options panel. Next to the options press +, and add a Search Template.

To configure the inspection to your question:

  1. In the search template box, add a variable followed by a method invocation, such as: $Instance$.get()
  2. Click edit variables and select $Instance$ from the list.
  3. In the 'Expression Constraints', add the expression type "Optional", and apply the constraint within type hierarchy.

Save your changes and run the inspection. (CTRL+Shift+Alt+I, type "Structural Search Inspection"). This should show you all instances of Optional.get().

Edit: In your question you ask if it's possible to get a compilation error. I believe this will strictly depend on how you're building your code. If you add an inspection and set the error level to 'Error', it should fail on Make/Compile but not on a 'mvn install'.

Upvotes: 0

Related Questions