How to design an immutable object with complex initialization

后端 未结 6 1214
北恋
北恋 2021-02-02 15:59

I\'m learning about DDD, and have come across the statement that \"value-objects\" should be immutable. I understand that this means that the objects state should not change aft

6条回答
  •  無奈伤痛
    2021-02-02 16:36

    Off the top of my head, two different answers come to mind ...

    ... the first, and probably simplest, is to use an object factory (or builder) as a helper that ensures you get things right.

    Object initialization would look like this:

    var factory = new ObjectFactory();
    factory.Fimble = 32;
    factory.Flummix = "Nearly";
    var mine = factory.CreateInstance();
    

    ... the second is to create your object as a conventional, mutable, object with a Lock() or Freeze() function. All of your mutators should check to see if the object has been locked, and throw an exception if it has.

    Object initialization would look like this:

    var mine = new myImmutableObject();
    mine.Fimble = 32;
    mine.Flummix = "Nearly";
    mine.Lock(); // Now it's immutable.
    

    Which method to take depends a lot on your context - a factory has the advantage of being convenient if you have a series of similar objects to construct, but it does introduce another class to write and maintain. A lockable object means there is only one class, but other users might get unexpected runtime errors, and testing is harder.

提交回复
热议问题