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,22 +41,28 @@ 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+ // safe get
54+ var unaryExpr = unaryExprOpt .get ();
55+ reportIssue (
56+ unaryExpr ,
57+ "%s operator (%s) should not be used with floating point variables" .formatted (
58+ isIncrement (unaryExpr ) ? "Increment" : "Decrement" ,
59+ unaryExpr .operatorToken ().text ()
60+ )
61+ );
62+ });
5763 }
5864
65+
5966 private static boolean isFloatingPoint (Type type ) {
6067 return type .isPrimitive (Primitives .FLOAT ) || type .isPrimitive (Primitives .DOUBLE );
6168 }
0 commit comments