This lesson demonstrates how to create a rule that reports a violation when assignment is used in an IF statement condition. Using assignment within if statement conditions is legal (so it won’t be caught by a compiler), but using a=b in IF statement conditions instead a==b is a common typographical error. In these cases, using assignment would prevent the code from functioning as intended.

The rule you will create in this lesson is included with Parasoft static analysis tools as PB.TYPO.ASI.

In this section:

Designing the Rule Pattern

Designing the rule pattern consists of creating a parent rule node and then adding qualifications to that node so that it fully expresses the code pattern that you wish to search for and remove during static analysis.

Creating the Parent Rule

  1. Choose File> New> Rule from the menu bar.
  2. Choose Java from the Dictionary menu in the Rule Tab of the New File panel.
  3. Enable the By Node option in the Rule Creation box.
  4. Choose the Statements> if node in the Node Selections box.
  5. Click OK. The if node appears in the right GUI panel.

Adding Additional Qualifications to the Parent Rule Node

  1. Right-click the if rule node and choose Condition from the shortcut menu.
  2. Choose a=b from the Expressions> Assignments category to check for instances where assignment is used in IF statement conditions.
  3. Click OK. Your rule should now look like this:

No additional qualifications are necessary for the rule to serve its purpose.

Specifying an Error Message

We need to specify the text printed when the rule is violated.

  1. Right-click the parent rule node (the Field rule node in this example) and choose Create Output> Display to open the Customize Output dialog.
  2. Enter the message you want delivered when this rule is violated, e.g., Avoid assignment in IF statement conditions
  3. Click OK. Your rule should now look like this:

Your rule now reports the specified error message when a developer uses assignment in IF statement condition. Your rule is functionally complete, but you may want to customize rule properties, such as severity, description, author, etc.. See Customizing Rule Properties for additional information.

Saving and Enabling Your Rule

Before you can check your rule, you need to save and enable it as described in Saving and Enabling Rules


  • No labels