magpiebrain

Sam Newman's site, a Consultant at ThoughtWorks

This little beauty was spotted in my struts code by a colleague of mine, clearly the result of too little coffee in the morning:



ActionErrors errors = errors = new ActionErrors();


Whilst I say this is a mistake, it actually complies and works. Here I’m assigning an object reference twice. It also works with multiple references:



Long p;
Long l = p = new Long(10);


Which results in both p and l are referencing the same object. It has to be said that I can’t think of a single legitimate reason why you’d want to do this – I blame the lack of coffee this afternoon for me spending even this much time on it…

Advertisements

3 Responses to “Brain hurting mistakes of our time”

  1. R.J.

    Yeah, it’s an interesting little known feature of Java assignment operators. In terms of ‘operator overloading’, it is essentially ‘returning’ the value of the assignment after performing the assignment on the variable.
    That’s why:
    boolean c = true;
    boolean b = false;
    if(b=c) {
    System.out.println(“text”);
    }
    compiles and prints out text; unlike:
    if(b==c) {

    }
    which doesn’t.

    Reply
  2. jef

    wheee!
    For that matter, you’ll also get the behavior that

    boolean c = true;
    boolean b = false;

    if(b=c) {
    System.out.println(“text”);
    }

    will always print, but

    if (c=b) {
    System.out.println(“text”);
    }

    will never print. Probably caused more than one VB developer to give up… Once I spent an hour trying to figure out why

    if (somemethodcall(c));
    {
    System.out.println(“text”);
    }

    would always print even as I stepped again and again through the method observing that I hadn’t botched the logic and that it really should be returning false…

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Basic HTML is allowed. Your email address will not be published.

Subscribe to this comment feed via RSS

%d bloggers like this: