1

After a build break, one developer complained it was because the previously available Clazz.clone() (not the real name of the class :)) has been removed, so his call to clz.clone() is breaking.

Upon which the author of Clazz advised that the client code be changed to use new Clazz(clz). \

Is there risk in implementing the clone method to return new Clazz(this)? What could go wrong?

Miserable Variable
  • 28,432
  • 15
  • 72
  • 133

3 Answers3

2

I don't believe there is risk in doing that, but it's unnecessary. Have your one developer change his function call.

// this is the same
var myClazz = thatClazz.clone();

// as this
var myClazz = new Clazz(thatClazz);

The new method uses something called a Copy Constructor which in my opinion looks cleaner than using .clone().

Further, a discussion should be had with your development team about modifying code that other modules are dependent on. Any methods or properties that are not private should have references checked before a change.

B-Rad
  • 383
  • 1
  • 14
2

The major difference is that clone is a method and a constructor is a constructor.

This means that

Clazz x = ...; 
Object xClone = x.clone()

returns whatever method clone of x.getClass() returns: a Clazz object or an object of a subclass of Clazz. Compare this to

Clazz x = ...;
Object xCopy = new Clazz( x );

which will give you a Clazz object, even when x references a SubClazz extends Clazz.

Presumably this doesn't matter to "the author of Clazz".

laune
  • 31,114
  • 3
  • 29
  • 42
  • There are many instances when `new Clazz(x)` should /not/ return a subclass but rather fail loudly. Slicing is not always good. – Miserable Variable Jul 25 '14 at 15:11
  • Now I see that you did not. Since I was asking specifically for risks in using clone I perhaps misinterpreted your description of difference between a method call and a constructor call to imply some benefit/loss analysis – Miserable Variable Jul 25 '14 at 15:38
2

There's lots of discussion around clone vs copy constructor on the internet, eg Clone() vs Copy constructor- which is recommended in java

Adding a clone method will work but given that this is all internal code, why introduce the extra complexity?

It does sound like you could do with a process to handle breaking changes. May be just do something simple such as mark clone as deprecated for a while to give developers a chance to stop using it.

I've seen people waste hours trying to maintain backward compatibility on internal apis and more hours arguing about trivial changes like this.

Community
  • 1
  • 1
matt helliwell
  • 2,574
  • 16
  • 24