2

I am reviewing some code. Inside that code there a constructor for an event listener, similar to the following code:

public class MyClass implements ActionListener {
  SomeOtherClass m_oc;

  public MyClass(SomeOtherClass oc) {
    if (null == oc) {
      throw new IllegalArgumentException("oc cannot be null");
    }
    m_oc = oc;
    m_oc.getClass();
  }


  @Override
  public void actionPerformed(ActionEvent e) {
    do_stuff();
  }

  private void do_stuff() {
    /* some more code here, but this code never uses m_oc */
  }
}

Now, my questions is: Why would who wrote this code call m_oc.getClass()?

That object (m_oc), which is an instance of SomeOtherClass is not used any where in the code apart from that location in the constructor.

Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192
feeling_lonely
  • 6,665
  • 4
  • 27
  • 53
  • There are many reasons to call `getClass()`, but here it is as you said dead code. Just delete it ;) – Dainesch Oct 23 '15 at 07:33
  • The call here doesn't make any sense, unless `getClass` has some sideffect I'm not aware of. – trooper Oct 23 '15 at 07:33
  • This could have been an artifact from an automatic refactoring. Maybe the value was saved before. It's completely pointless now, since `getClass()` has no side effects. – Kevin Krumwiede Oct 23 '15 at 07:34

2 Answers2

5

No, there is no reason for doing this. The getClass method is non-virtual and has no side effect. Consequently, there is no way this statement itself has any effect. Furthermore, there is already an explicit check for null of the assigned reference, therefore this call cannot provoke a NullPointerException.

Some people like using getClass as a "fast" or "concise" null-check because of the way that the JIT treats this method. This is not longer true for modern VMs and does not expose your intention appropriately. Also, getClass has strange side-effects for C2 compilation. I would expect this to be the result of an incomplete refactoring. Maybe your version history reveals the origins of this statement.

Community
  • 1
  • 1
Rafael Winterhalter
  • 42,759
  • 13
  • 108
  • 192
0

There is no reason to call that method at all in that place. That's redundant since you are just calling and not receiving any output or that method won't affect the state of your object.

Can be removed.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307