vendredi 7 janvier 2022

Is there a better method to apply some operation on a group of properties?

Not sure this is the place for question like this, but give a try anyway. Say my web api is returning some really wide response (e.g. 900 properties), in the object, I have these:

public class WideOutput{
     public datetime Date1 {get;set;}
     public decimal Value1 {get;set;}
     ....
     public decimal Value20 {get;set;}
     public datetime Date2 {get;set;}
     public decimal Value21 {get;set;}
     ....
     public decimal Value40 {get;set;}
     public decimal SomeOtherValues {get;set;}
     public decimal SomeOtherValues860 {get;set;}
}

This is the requirement:

  1. For properties Value1 to Value20, apply exchange rate from Property Date1
  2. For properties Value21 to Value40, apply exchange rate from Property Date2
  3. For other properties, just output raw value.

Of course I could do this:

var output = SomeService.LoadWideOuput();
var exchangeRateFroDate1 = ExchangeService.GetRate(output.Date1);
var exchangeRateFroDate2 = ExchangeService.GetRate(output.Date2);
output.Value1 = output.Value1* exchangeRateFroDate1 
....
output.Value20 = output.Value1* exchangeRateFroDate20

output.Value21 = output.Value1* exchangeRateFroDate21 
....
output.Value40 = output.Value1* exchangeRateFroDate40 

However, that method will be really long and very boring to write.

Another way I can think of is using attribute and reflection. Something like this:

public class WideOutput{
     public datetime Date1 {get;set;}
     [ExchangeField(LinkedTo="Date1")]
     public decimal Value1 {get;set;}
     ....
     [ExchangeField(LinkedTo="Date1")]
     public decimal Value20 {get;set;}
     public datetime Date2 {get;set;}
     [ExchangeField(LinkedTo="Date2")]
     public decimal Value21 {get;set;}
     ....
     [ExchangeField(LinkedTo="Date2")]
     public decimal Value40 {get;set;}
     public decimal SomeOtherValues {get;set;}
     public decimal SomeOtherValues860 {get;set;}
}

Then in the method I could do this (pseudo code idea only):

var output = SomeService.LoadWideOuput();
var exchangeRateFroDate1 = ExchangeService.GetRate(output.Date1);
var exchangeRateFroDate2 = ExchangeService.GetRate(output.Date2);
var exchangeRateDate1Fields = ReadAttributesRelatedAndReturnPropertyList(typeof(output), "Date1");
SetPropertyValueUsingReflection(exchangeRateDate1Fields, output, exchangeRateFroDate1);
var exchangeRateDate2Fields = ReadAttributesRelatedAndReturnPropertyList(typeof(output),"Date2");
SetPropertyValueUsingReflection(exchangeRateDate2Fields , output, exchangeRateFroDate2 );

Technically it will work, but as I use reflection to set value, it certainly will be slower. In a web API environment, I do need to pay attention to performance.

I am wondering maybe there are some other ways that I haven't explored?





Aucun commentaire:

Enregistrer un commentaire