How to detect java class level variable in Sonar cloud

Recently in team , some of the developers introduced class level variables, which were used later in functions, had dynamic values.
As these variables were not constant , these variables were shared across all http request and threads. These variables values got mixed up with different http requests/threads in same class and APIs were behaving un-expectedly.

During debugging the issue , we found the cause and changed these class level variable to local variables.

To avoid this issue in future release , I wanted to know is there any way by which class level variables (which are not constant/final) can be detected and showed as issues after scan ? Kindly advice.

Some example of class level variables which caused issues are below

package purchase.cancellation.client;
@Service
public class EmailServiceClient {
    private int refundAmount;
    private int penalty;
    private int totalAmount;
    private void checkBoardedAmount(Order order) {
        totalAmount = refundAmount - penalty;
		order.setTotalAmount(totalAmount);
    }
}

Hi @BansalGaurav,
I don’t believe such a rule exists at the moment.
We do have S1450 looking at fields used in a single method but the implementation specifically discards fields that are used in multiple methods.

And in your specific case, S1450 properly flags totalAmount as a candidate to be a local variable.
But if you use totalAmount in another method, even to serve as temporary storage like in your example, then S1450 no longer flags the field.

@Service
  public class EmailServiceClient {
    private int refundAmount;
    private int penalty;
    private int totalAmount; // No longer flagged as an issue because used in multiple methods

    private void checkBoardedAmount(Order order) {
      totalAmount = refundAmount - penalty;
      order.setTotalAmount(totalAmount);
    }

    private void checkBoardedAmountAgain(Order order) {
      totalAmount = refundAmount - penalty;
      order.setTotalAmount(totalAmount);
    }
  }

But that sounds like a nice idea for a rule :slight_smile: I will have a look at what we can do on this topic.

Cheers,

Dorian

1 Like

Thanks @Dorian_Burihabwa for reply!
Yes , As you mentioned S1450 will not help for our scenario. It would be good if you can take up and create a custom rule to detect such variables.

Thanks,
Gaurav