Video in progress

Strong Middle 🧱 OOP and SOLID

Why are `Cloneable` and `clone()` called bad design, and what are better ways to copy an object?

Cloneable is a marker interface with no methods that quietly changes the behavior of Object.clone(). clone() bypasses constructors, makes a shallow copy, throws a checked exception, and doesn't work with final fields. Use a copy constructor or a static factory instead.

📖 Answer

The problems with clone():

  • The Cloneable interface has no clone() method. It only signals that Object.clone() is "allowed", which goes against the usual meaning of an interface.
  • Object.clone() is protected and throws CloneNotSupportedException (checked), so every override has try/catch noise.
  • The constructor isn't called: validation and invariants in the constructor are bypassed.
  • A shallow copy: a List, array or other mutable object inside is shared with the original. For a deep copy you have to reassign the field, but you can't assign a new value to a final field inside clone().
  • The inheritance chain: every class must call super.clone() correctly, and if one of them does a new, the whole mechanism breaks.

Better options:

public final class Draft {
    private final String title;
    private final List<String> tags;

    public Draft(Draft other) {                 // copy constructor
        this(other.title, other.tags);
    }

    public Draft(String title, List<String> tags) {
        this.title = title;
        this.tags = List.copyOf(tags);          // an immutable copy (shallow, but Strings are immutable anyway), and validation runs
    }

    public static Draft copyOf(Draft d) { return new Draft(d); }
}

What is good about it: it goes through the constructor, it works with final fields, there is no exception, and it can accept an interface type (like new ArrayList<>(anyCollection)).

Immutable objects don't need copying at all: sharing one instance is safe. For arrays, array.clone() is still a normal and short option, which is an exception to this rule.