How to get IntelliJ to warn about unsafe practices Option.get ()

Some of my colleagues who were not very attentive went around Optional instances and considered it safe to call get on them without first calling isPresent .

I know ... this should not happen, but the type system will not stop them!

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

+6
source share
2 answers

IntelliJ 2016.1 supports this finished product!

By default, calling get() without checking with isPresent() first give a warning, but you can go to the "Checks" screen and set Optiong.get() without isPresent() check to have the severity of "Error" if you prefer.

+2
source

You can use the check for the flag instance and show you a warning / error. This can be exceptional for the end.

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

  • Open the settings (CTRL + ALT + S) and search for checks.
  • In the tree, find "General" and under it "Inspection of structural search".
  • In the description you will see a panel of cruelty / parameters. Next to the options, click + and add a search template.

To customize the check to your question:

  • Add a variable to the search template field followed by a method call, for example: $ Instance $ .get ()
  • Click "Edit Variables" and select "$ Instance" from the list.
  • In Expression Constraints, add an optional expression type and apply the constraint in the type hierarchy.

Save the changes and check. (CTRL + Shift + Alt + I, type "Check structural search"). This should show you all instances of Optional.get ().

Edit: in your question, you are asking if it is possible to get a compilation error. I believe that this will strictly depend on how you build your code. If you add a check and set the error level to Error, it should fail in Make / Compile, but not in mvn install.

0
source

All Articles