문제

I'm trying to figure out what is the best way to update a polymorphic child entity inside an aggregate root. For reference, let's say I have a ShippingContainer root entity that stores Cargo objects; there are many types of Cargo objects, for example, BigCargo, HazardousCargo, etc., each with their own unique properties.

I was reading this question: Update an entity inside an aggregate

The answer to this question seems to indicate I should place the ChangeCargo method on the ShippingContainer object taking some kind of DTO parameters object. My question is whether or not this is still best practice when the object you are trying to update is polymorphic (do I now need a hierarchy of DTO objects mirroring the Cargo object types?), or should I be doing something else?

도움이 되었습니까?

해결책

If the ChangeCargo use case knows the specific type of cargo it wishes to change, then there would likely be specific versions of this method for each cargo type.

If however, the change is itself agnostic of the cargo type, then it would be best to make use of polymorphism and delegate the update to each cargo subtype. The change could be expressed with a DTO, a value object or a few parameters.

For example (C#):

class ShippingContainer
{
    List<Cargo> cargos;

    public void ChangeCargo(string cargoId, DateTime expectedArrival, ...)
    {
        var cargo = this.cargos.FirstOrDefault(cargo => cargo.Id == cargoId);
        cargo.Change(expectedArrival, ...);
    }
}

class BigCargo : Cargo
{
    public void Change(DateTime expectedArrival, ...) { }
}

class HazardousCargo : Cargo
{
    public void Change(DateTime expectedArrival, ...) { }
}

The parameters starting with expectedArrival could be a DTO or whatever best represents the change.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top