|
|
|
|
|
by plumarr
1249 days ago
|
|
It can't but that's not due to the proposed solution for withers. The cause is Records themselves. Record are immutable on purpose and you want to add a mutation constraint whish will not play nicely. The proposed constraint will be triggered in this case : var r = retrieveFromDb(); (value is A)
r = r.with(C) -> throw an exception
But this only work if B is generated by the wither. If I deconstruct the record manually and reconstruct with C manually, it'll work. So this offer no garantee that this transition will never occur.I would even argue that this constraint can't be implemented at the level of the class, at least if the class is only a data carrier without external dependencies. |
|
>It can't but that's not due to the proposed solution for withers.
This has nothing to do with withers. It can't be implemented simply because it is a constraint on a specific transition of state. There's no transition of state in constructor.
>Record are immutable on purpose and you want to add a mutation constraint whish will not play nicely.
The purpose of immutability is not to create constant objects, but to prevent side effects from sharing mutable objects: state modifications are possible, they are simply reflected in a modified copy of object. That also means that my argument stands also for entities modeled as classes with final fields, it has nothing to do with specifics of records.
Indeed, the fact that we have a constructor from which we can build any valid state and that we can deconstruct an immutable object means that we can bypass transition validations, but that will require some extra effort from developer and explicit demonstration of intent compared to simply using `with` block. Compare this:
this: and this: