I've got a record that I use for making update requests via json/Jackson:
public record UpdateRequest(
Optional<String> field1,
Optional<LocalDate> field2,
Optional<@Max(24) Integer> field3,
...
Optional<String> specialField) {}
I want to prevent updates from happening if the entity is marked as closed
, except for specialField
. That can always be used to update the entity.
While the entity is closed
, I'd want to allow an update request like:
{
"specialField": "newValue"
}
But prevent one like:
{
"field1": "newValue"
}
I'm struggling to come up with a good solution for checking whether the update can be applied. This is what I have:
public boolean isUpdateValid(Entity entity, UpdateRequest updateRequest) {
return !entity.isClosed()
|| (updateRequest.field1().isEmpty()
&& updateRequest.field2().isEmpty()
&& updateRequest.field3().isEmpty());
}
But this is pretty error-prone, because no one will update isUpdateValid
when new fields are added to UpdateRequest
. Does anyone have suggestions about better ways to structure this so that it is more maintainable as UpdateRequest
changes?
I came up with the following solution that might be a little janky, but should work.
public boolean isUpdateValid(Entity entity, UpdateRequest updateRequest) {
return !entity.isClosed() || new UpdateRequest(Optional.empty(), Optional.empty(), ..., updateRequest.specialField()).equals(updateRequest);
}
This should work since records have generate an equals
method, but won't work if you override it in your record.