I would like to be able to copy an object and only change a few values. I have come up with two different ways to do this.
// OPTION A - create a copy constructor and use property
// initialization to change values
class SomeObject {
public string PropertyA { get;set; }
public string PropertyB { get;set; }
public SomeObject() { }
public SomeObject(SomeObject copyFrom) {
PropertyA = copyFrom.PropertyA;
PropertyB = copyFrom.PropertyB;
}
}
var original = new SomeObject() {
PropertyA = "original value",
PropertyB = "some other original value",
}
// replace only the values I want to replace
var partialCopy = new SomeObject(original) {
PropertyA = "some new value different from original",
};
// OPTION B - create an Option<T> type and use that
// used as constructor paramaters
public class Option<T> {
// used in the case where you want
// the default value of a type instead
// of the original value (see usage below)
public static readonly Default = new Option<T>(default(T));
public T Value { get; private set; }
public Option(T value) {
Value = value;
}
public static implicit operator T(Option<T> o) {
return o.Value;
}
public static implicit operator Option<T>(T value) {
return new Option<T>(value);
}
}
public class SomeObject {
public string PropertyA { get; set; }
public string PropertyB { get; set; }
public SomeObject() { }
public SomeObject(SomeObject toCopy,
Option<string> propertyA = null,
Option<string> propertyB = null)
{
PropertyA = propertyA ?? toCopy.PropertyA;
PropertyB = propertyB ?? toCopy.PropertyB;
}
}
var original = new SomeObject() {
PropertyA = "original value",
PropertyB = "some other original value",
};
// replace only the values I want to replace
var partialCopy = new SomeObject(original,
propertyA: "new value");
The first implementation has much less code to maintain, but you can’t enforce things in the constructor. The second is a bit more complicated due to the Option<T>
class but you can, in effect, enforce rules better in a constructor at object creation. Do you think the constructor safety of OPTION B
overrides the complexity, making it the better choice. Or should I use the simpler OPTION A
due to ease of maintenance?
These are simple data transfer objects. They generally have a lot of properties. I’m trying to avoid creating objects like template, templateB, templateB.2, etc.
when I can just copy the current object and change the properties I need. For example, properties A,B, and C need to be set to this value when a particular rule passes. However further in the process, properties D,E, and F will need different values based on other rules. I’m trying to avoid code like the following:
// I'm trying to avoid this
ResponseObject SomeMethod(bool inputA, bool inputB) {
var myObject = CreateObjectFromTemplateA(); // has same values for A,B,C
if(inputA) {
myObject.D = "some value";
myObject.E = "some value";
myObject.F = "some value";
} else if (inputB) {
myObject.D = "some other value";
myObject.E = "some other value";
myObject.F = "some other value";
}
return myObject;
}
// and do something like this instead
ResponseObject SomeMethod(bool inputA, bool inputB) {
var defaultValue = CreateFromTemplateA()
return inputA ? new ResponseObject(defaultValue) { D = "some value",
E = "some value",
F = "some value",},
: inputB ? new ResponseObject(defaultValue) { D = "some other value",
E = "some other value",
F = "some other value",},
: defaultValue;
}
// in some cases it's as simple as one property change
// and here is where the first method of property initialization
// breaks down
ResponseObject SomeMethod(bool inputA, bool inputB) {
return new ResponseObject(CreateFromTemplateA()) {
D = inputA ? "some value"
: inputB ? "some other value
: CreateFromTemplateA(), // a second object created
};
}
// here is where the constructor initialization helps
ResponseObject SomeMethod(bool inputA, bool inputB) {
return new ResponseObject(CreateFromTemplateA(), // with this method CreateFromTemplateA() could be a property instead of a method call
d: inputA ? "someValue"
: inputB ? "someValue"
: null // null here indicates use the property value from CreateFromTemplateA()
);
}
8
I would do it via fluid Interface / method-chaining:
class Person {
[...]
public Person WithFirstName( String FirstName ){
this.FirstName=FirstName;
}
public Person WithLastName( String LastName ){
this.LastName=LastName;
}
[...]
public Person Clone(){
Person clone = new Person()
.WithFirstName(this.FirstName)
.WithLastName(this.LastName)
[...]
return clone;
}
}
So if you need an object with different values, you would do it with:
Person personB=personA.Clone()
.WithFirstName("John");
This makes your intention clear:
1) You send a message to a person-Object: clone yourself
2) You send a new message to the clone, that you wish it with a different first name.
class SomeObject {
public string PropertyA { get;set; }
public string PropertyB { get;set; }
public SomeObject WithABC(string value) {
var clone = MemberwiseClone();
clone.PropertyA = value;
clone.PropertyB = value;
clone.PropertyC = value;
return this;
}
}
var copy = original.WithABC("another value");
There are several ways to achieve this.
As mentioned in the other comments, you must consider if the object is a simple property object or has property references to other objects, and who “owns” or “manages” those object references or objects.
Example of simple object:
public class PersonClass
{
public string FirstName;
public string LastName;
public DateTime BirthDate;
public bool IsMarried;
public PersonClass GetSimpleCopy()
{
PersonClass Result = new PersonClass();
Result.FirstName = this.FirstName;
// assign other properties
return Result;
}
} // class PersonClass
Check that this is a very simple way to duplicate an object.
Note that I skipping “copying” constructors.
Example of object with references to other objects, that are managed (“created” / “destroyed” ) by the main object:
public class PersonClass
{
public string FirstName;
public string LastName;
public DateTime BirthDate;
public bool IsMarried;
public PersonClass GetSimpleCopy() { ... }
} // class PersonClass
public class ItemClass
{
public string ProductID;
public string ProductName;
public Float Price;
public int Qty;
public ItemClass GetSimpleCopy() { ... }
} // class ItemClass
public class SaleClass
{
protected bool _Referenced;
public float Total;
public PersonClass Customer;
public List<ItemClass> Items;
public bool Referenced()
{
bool Result = false;
Result = this._Referenced;
return Result;
} // bool Referenced()
public ItemClass GetSimpleCopy()
{
ItemClass Result = new ItemClass();
Result._Referenced = false;
Result.Total = this.Total;
// explicitly return "empty"
Result.Customer = null;
Result.Items= new List<ItemClass>();
return Result;
} // ItemClass GetSimpleCopy()
public ItemClass GetReferencedCopy()
{
ItemClass Result = new ItemClass();
Result._Referenced = true;
Result.Total = this.Total;
// explicitly return references
Result.Customer = this.Customer;
Result.Items = this.Items;
return Result;
} // ItemClass GetReferencedCopy()
public ItemClass GetComplexCopy()
{
ItemClass Result = new ItemClass();
Result._Referenced = false;
Result.Total = this.Total;
// explicitly make a copy of subobjects
Result.Customer = this.Customer.GetSimpleCopy();
// copy each item
Result.Items = this.Items.GetSimpleCopy();
return Result;
} // ItemClass GetComplexCopy()
} // class SaleClass
Remember that O.O. Programming Languages that support object references, is preferred to copy the reference instead of the whole object.
Yet, there are cases where the full copy is required. In case of complex or composed objects, its better to provide a property flag that indicates if subobjects are just references or are managed by the main object.
Sometimes, a main object may manage some subobjects, but, also have a reference to other objects that may not be required to be managed or to be copied. In those cases, a flag for each subobject helps.
Note that the function “Referenced” indicates if a composed / complex object manages subojects, and, the different copy methods indicate what kind of copying was applied.
Note that, I intentionally skip constructors, and use specific methods with a more clear identifier.
Cheers.