Uploaded image for project: 'Rules Repository'
  1. Rules Repository
  2. RSPEC-2975

"clone" should not be overridden

    XMLWordPrintable

    Details

    • Type: Code Smell Detection
    • Status: Active
    • Resolution: Unresolved
    • Labels:
    • Message:
      Remove this "clone" implementation; use a copy constructor or copy factory instead.
    • Default Severity:
      Blocker
    • Impact:
      High
    • Likelihood:
      High
    • Default Quality Profiles:
      Sonar way
    • Covered Languages:
      Java
    • Remediation Function:
      Constant/Issue
    • Constant Cost:
      30min
    • Analysis Scope:
      Main Sources
    • Implementation details:
    • Checkstyle:
      NoClone

      Description

      Many consider clone and Cloneable broken in Java, largely because the rules for overriding clone are tricky and difficult to get right, according to Joshua Bloch:

      Object's clone method is very tricky. It's based on field copies, and it's "extra-linguistic." It creates an object without calling a constructor. There are no guarantees that it preserves the invariants established by the constructors. There have been lots of bugs over the years, both in and outside Sun, stemming from the fact that if you just call super.clone repeatedly up the chain until you have cloned an object, you have a shallow copy of the object. The clone generally shares state with the object being cloned. If that state is mutable, you don't have two independent objects. If you modify one, the other changes as well. And all of a sudden, you get random behavior.

      A copy constructor or copy factory should be used instead.

      This rule raises an issue when clone is overridden, whether or not Cloneable is implemented.

      Noncompliant Code Example

      public class MyClass {
        // ...
      
        public Object clone() { // Noncompliant
          //...
        }
      }
      

      Compliant Solution

      public class MyClass {
        // ...
      
        MyClass (MyClass source) {
          //...
        }
      }
      

      See

      See Also

      • S2157 - "Cloneables" should implement "clone"
      • S1182 - Classes that override "clone" should be "Cloneable" and call "super.clone()"

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              Unassigned Unassigned
              Reporter:
              ann.campbell.2 Ann Campbell
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated: