Bug 28937 - Compiler Problem Marker: Accidental Boolean Assignment
Summary: Compiler Problem Marker: Accidental Boolean Assignment
Status: VERIFIED FIXED
Alias: None
Product: JDT
Classification: Eclipse Project
Component: Core (show other bugs)
Version: 2.1   Edit
Hardware: All All
: P3 enhancement (vote)
Target Milestone: 3.0 M1   Edit
Assignee: Philipe Mulet CLA
QA Contact:
URL:
Whiteboard:
Keywords:
Depends on:
Blocks:
 
Reported: 2003-01-01 13:04 EST by Simon Archer CLA
Modified: 2003-06-06 09:29 EDT (History)
0 users

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description Simon Archer CLA 2003-01-01 13:04:00 EST
It would be useful for Eclipe to include a Compiler Problem Marker to flag the 
case where the assignment operator in a boolean expression was mistakenly used 
when the identity operator was intended.  Consider the following legal Java 
code:

public class AssignmentTest {
  private boolean test() {
    return true;
  }
	
  public void start() {
    boolean value = false;
	
    if (value = test()) {
      System.out.println("Passed");
    }
  }
}


In the start() method did the author really mean to use the assignment 
operator?  Or perhaps he intended to use the identity operator:

    if (value == test()) {
      System.out.println("Passed");
    }


Unfortunately, just like C, Java's assignment operator returns a value that can 
lead to problematic code as shown above.  I would argue that in most cases the 
author intended to use the identity operator.  I would like to suggest that 
Eclipse includes a Compiler Problem Marker to flag this problem and that the 
default value be "Warning".  This marker should apply to complex boolean 
expressions such as if(...), while(...), do while(...).  There may well be 
other places where this marker can be applied.

The following code should probably NOT be flagged by the marker:

    // Added parens with explicit boolean identity test.
    if ((value = test()) == true) {
      System.out.println("Passed");
    }


And possibly even the following:

    // Added parens with implicit boolean identity test.
    if ((value = test())) {
      System.out.println("Passed");
    }


BTW, a well known coding conventions that helps prevents this problem involves 
reordering the boolean expression as follows:

    if (test() = value) {  // COMPILE ERROR!
      System.out.println("Passed");
    }

Compile Error: "The left-hand side of an assignment must be a variable"
Comment 1 Philipe Mulet CLA 2003-01-08 05:43:25 EST
Sounds like a good candidate for an optional warning.
Will consider post 2.1
Comment 2 Philipe Mulet CLA 2003-04-04 02:17:02 EST
reopen
Comment 3 Philipe Mulet CLA 2003-04-07 09:50:21 EDT
Optional compiler problem added. Defaulting to warning.
Fixed
Comment 4 David Audel CLA 2003-06-06 09:29:02 EDT
Default value is 'Ignore'

Verified.