Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable Design: Dealing with Constructor Insanity

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?

like image 893
Billy ONeal Avatar asked Sep 06 '12 00:09

Billy ONeal


1 Answers

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();
like image 113
Alexei Levenkov Avatar answered Oct 05 '22 05:10

Alexei Levenkov