1717package org .sonar .java .checks ;
1818
1919import java .util .List ;
20+ import java .util .Optional ;
2021import org .sonar .check .Rule ;
2122import org .sonar .plugins .java .api .IssuableSubscriptionVisitor ;
2223import org .sonar .plugins .java .api .semantic .Type ;
@@ -40,20 +41,24 @@ public List<Tree.Kind> nodesToVisit() {
4041
4142 @ Override
4243 public void visitNode (Tree tree ) {
43- if (
44- tree instanceof UnaryExpressionTree unaryExpr &&
45- unaryExpr .expression () instanceof IdentifierTree identifier &&
46- // above condition should always be true, just used to pattern match safely
47- isFloatingPoint (identifier .symbolType ())
48- ) {
49- reportIssue (
50- unaryExpr ,
51- "%s operator (%s) should not be used with floating point variables" .formatted (
52- isIncrement (unaryExpr ) ? "Increment" : "Decrement" ,
53- unaryExpr .operatorToken ().text ()
54- )
55- );
56- }
44+ var unaryExprOpt = Optional .of (tree )
45+ .filter (UnaryExpressionTree .class ::isInstance )
46+ .map (UnaryExpressionTree .class ::cast );
47+ unaryExprOpt
48+ .map (UnaryExpressionTree ::expression )
49+ .filter (IdentifierTree .class ::isInstance )
50+ .map (IdentifierTree .class ::cast )
51+ .filter (identifier -> isFloatingPoint (identifier .symbolType ()))
52+ .ifPresent (identifier -> {
53+ var unaryExpr = unaryExprOpt .get (); // safe get
54+ reportIssue (
55+ unaryExpr ,
56+ "%s operator (%s) should not be used with floating point variables" .formatted (
57+ isIncrement (unaryExpr ) ? "Increment" : "Decrement" ,
58+ unaryExpr .operatorToken ().text ()
59+ )
60+ );
61+ });
5762 }
5863
5964 private static boolean isFloatingPoint (Type type ) {
0 commit comments