mercredi 6 novembre 2019

Pattern or approach for accessing parent object properties deeper in the object graph

We have scenarios where objects that are 'deeper' in the object graph need to have values updated based on the value of an ancestor. E.g. consider a mapping exercise where we are mapping values of an object that is coming in from a web view. We have the original persisted object as it exists in the database/store, and we have the mutated object that is coming in from the view. Given the 'schema' below for a visual, if we are mapping the incoming object from the view to a persisted 'twin' from the database, and we want to set the value of the coverage deductible based on the value of the policy default deductible, is there a way to do this without passing along a reference to the parent object?

{
   Policy: {
     DefaultDeducitble: 1000
     LocationCollection: [{ 
           Location: {
            BuildingCollection: [{
               Building: {
                CoverageCollection: [{
                  Coverage: { DefaultDeductible: nulll}
                }]
              }
          }]
          }
       }]
  }
}

Our mappers map one level of an objects hierarchy, so we would have something like:

class PolicyMapper { /// maps policy and calls a location collection mapper }
class LocationCollectionMapper { /// calls a location mapper for each location }
class LocationMapper {///maps the location and calls building collection mapper }
class BuildingCollectionMapper { /// calls a building mapper for each building }
class BuidlingMapper {///maps the buidling and calls coverage collection mapper }
class CoverageCollectionMapper { /// calls a coverage mapper for each coverage }
class CoverageMapper {///maps the coverage, this is where we want a value from the Policy level }

So the questionwould be, how can we access the Policy level information in the CoverageMapper without passing the the Policy object throughout the mapping hierarchy? One idea was to have a transient cache that we can query. I don't really know if this exists...or if this is a good idea or an antipattern...however it would look something like:

public class TransientPolicyCache {
   ///code to load the cache and retreive stuff
   public Policy Get() { //returns the policy  }
}

public class CoverageMapper {
   public CovergaeMapper(TransientPolicyCache cache) { ///cache is provided by ioc }

   public Coverage Map(Coverage target, Coverage source){  
     //need the policy
     var policy = _cache.Get();
    // do the things
   }
}

Aucun commentaire:

Enregistrer un commentaire