JDK-6582394 : (RFE) "Assignment has no effect" should be compile error.
  • Type: Enhancement
  • Component: specification
  • Sub-Component: language
  • Affected Version: 7
  • Priority: P5
  • Status: Closed
  • Resolution: Not an Issue
  • OS: windows_xp
  • CPU: x86
  • Submitted: 2007-07-18
  • Updated: 2010-04-04
  • Resolved: 2007-07-20
There are many cases where an object reference gets inadvertently assigned to itself (see example).  There is no reason whatsoever for the programmer doing this, since it is an ineffectual operation.  Therefore, the operation almost always causes a bug.  In IDE's such as Eclipse, this produces a complie warning.  Based on the scope of the variable, the compiler could eliminate this problem entirely by recognizing this as a compile error.

I have seen an unusually large number of bugs of this type produced by developers who, in general, ignore compile errors that may or may have not been produced by their particular IDE.  While there are workarounds such as alternative naming conventions, reconfiguring an IDE to mark this as an error, etc., making this an error would absolutely prevent programmers from making this common mistake, thereby reducing bugs in general.  I have never seen an occurrence of self-assigning an object reference that was intentional and can't imagine any reason for doing so.  Yes, it would break existing code, but only a) bugs or b) ineffectual lines of code.  Just flip on this option in Eclipse to regard this as an error in any very large Java project and you will likely find several bugs.  IMHO, this should always be a compile error produced by the JDK.

A compile error stating that the assignment has no effect.
Nothing, although some IDE's such as Eclipse produce a compile warning.

---------- BEGIN SOURCE ----------
// Example.java
public class Example {
    private int foo;
    public void setFoo(int foo) {
        foo = foo; // assignment has no effect due to improper scope

---------- END SOURCE ----------

Alternative naming conventions, or reconfiguring an IDE to mark this as an error.  However, these are proactive solutions that developers in general don't follow.

EVALUATION I have some sympathy with the problems caused by the anti-pattern in setFoo, but it is not for the language to start breaking programs when we do not know the cost of fixing them. Reporting self-assignments is a job for tools. In particular, it is a job for tools because aliasing makes it Really Hard to know the effect of an assignment in general. Heuristics and formalisms to understand aliasing are proposed all the time in the research community. A toy example that would not be caught by a syntactic rule: void setFoo(Object foo) { Object foo2 = foo; // Alias x for some reason foo = foo2; // This assignment has no effect. Should we give an error? }