For various reasons I'd like to start using more immutable types in designs. At the moment, I'm working with a project which has an existing class like this:
public class IssueRecord
{
// The real class has more readable names :)
public string Foo { get; set; }
public string Bar { get; set; }
public int Baz { get; set; }
public string Prop { get; set; }
public string Prop2 { get; set; }
public string Prop3 { get; set; }
public string Prop4 { get; set; }
public string Prop5 { get; set; }
public string Prop6 { get; set; }
public string Prop7 { get; set; }
public string Prop8 { get; set; }
public string Prop9 { get; set; }
public string PropA { get; set; }
}
This class represents some on-disk format which really does have this many properties, so refactoring it into smaller bits is pretty much out of the question at this point.
Does this mean that the constructor on this class really needs to have 13 parameters in an immutable design? If not, what steps might I take to reduce the number of parameters accepted in the constructor if I were to make this design immutable?
To decrease number of arguments you can group them into sensible sets, but to have truly immutable object you have to initialize it in constructor/factory method.
Some variation is to create "builder" class that you can configure with fluent interface and than request final object. This would make sense if you actually planning to create many of such objects in different places of the code, otherwise many arguments in one single place maybe acceptable tradeoff.
var immutable = new MyImmutableObjectBuilder()
.SetProp1(1)
.SetProp2(2)
.Build();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With