Code in Java but should be readable also for c#...
Let's assume I have a class with some reference types. Example:
class MyClass {
private int uniqueId;
private double doubleValue;
private MyReferenceType refType1;
// ...
public MyClass(int id, double doubleValue, MyReferenceType refType){
this.id = id;
this.doubleValue = doubleValue;
this.refType1 = refType; // seems dangerous - I want to create new object with the same state instead of adding a reference to an existing one...
}
// ...
}
The question is what approach of constructing such an object do you prefer:
Option 1 In constructor:
public MyClass(int id, double doubleValue, MyReferenceType refType){
// ...
this.refType1 = new MyReferenceType(refType); // MyReferenceType has some "copy" constructor
}
In code:
MyClass mc = new MyClass(1, 1.0, someRefTypeInstance);
or
Option 2: In constructor:
public MyClass(int id, double doubleValue, MyReferenceType refType){
// ...
this.refType1 = refType;
}
In code:
MyClass mc = new MyClass(1, 1.0, new MyReferenceType(someRefTypeInstance));
Which approach do you find more reasonable and you use in practice?
MyReferenceType
, a third option is to make it immutable. \$\endgroup\$