New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement RuleApplicationTrace.clone correctly #34

Closed
LorenzoBettini opened this Issue Sep 4, 2014 · 0 comments

Comments

Projects
None yet
1 participant
@LorenzoBettini
Copy link
Collaborator

LorenzoBettini commented Sep 4, 2014

As reported by Sonarqube:

super.clone() should be called when overriding Object.clone()

The usual convention for Object.clone() according to Oracle's Javadoc is that:
x.clone() != x
x.clone().getClass() == x.getClass()
x.clone().equals(x)
Obtaining the object that will be returned by calling super.clone() helps to satisfy those invariants:
super.clone() returns a new object instance
super.clone() returns an object of the same type as the one clone() was called on
Object.clone() performs a shallow copy of the object's state
For example, the following code:
class BaseClass implements Cloneable {
  @Override
  public Object clone() throws CloneNotSupportedException {    // Non-Compliant - should return the super.clone() instance
    return new BaseClass();
  }
}

class DerivedClass extends BaseClass implements Cloneable {
  /* Does not override clone() */

  public void sayHello() {
    System.out.println("Hello, world!");
  }
}

class Application {
  public static void main(String[] args) throws Exception {
    DerivedClass instance = new DerivedClass();
    ((DerivedClass) instance.clone()).sayHello();              // Throws a ClassCastException because invariant #2 is violated
  }
}
should be refactored into:
class BaseClass implements Cloneable {
  @Override
  public Object clone() throws CloneNotSupportedException {    // Compliant
    return super.clone();
  }
}

class DerivedClass extends BaseClass implements Cloneable {
  /* Does not override clone() */

  public void sayHello() {
    System.out.println("Hello, world!");
  }
}

class Application {
  public static void main(String[] args) throws Exception {
    DerivedClass instance = new DerivedClass();
    ((DerivedClass) instance.clone()).sayHello();              // Displays "Hello, world!" as expected. Invariant #2 is satisfied
  }
}
squid:S1182 Reliability > Architecture

@LorenzoBettini LorenzoBettini added this to the 1.6.0 milestone Sep 4, 2014

@LorenzoBettini LorenzoBettini added the bug label Sep 4, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment