Friday, October 14, 2011

Instanceof and equals

Today I stumbled upon a code that someone committed to the project.
    if ( this.getClass().equals(A.class) )
Although it was a working piece of code and so far I believe no bug was caused by it, however, I think it's a little dangerous code. It depends on the context and what this method is intended to do, but most likely the programmer just wants to know whether this object is from class A. Very unlikely that someone will create a method to check 'this' is an object of exactly class A (something is wrong in the design then?). So preferably, instanceof should be used instead of using equals, unless you know exactly what you are doing.
    if ( (this instanceof A) )

This getClass violates  Principle of least astonishment . It means in ambiguous cases, it should be designed so that user is least surprised. 

About this principle, wikipedia has a good example. Let's say you are typing a password on some web and then suddenly your friend sends a chat message and the instant messenger took the focus. Ops! You pressed enter to find that your password is just sent to your friend. Although for instant messaging it may be a nice feature to take the focus so that you can respond quickly, however to avoid these kinda surprises, this need to be avoided.

A good discussion about this topic:

No comments:

Post a Comment