I am currently writing a method that fills in the missing properties of an object. The object has had some values set from the database, but if any are empty, then it goes off to an alternative data source (long story).
What this means is that my code has become a little bit like the snippet below
if(string.IsNullOrEmpty(myObject.FieldA))
myObject.FieldA = UpdateFromMethod("FieldA");
if(string.IsNullOrEmpty(myObject.FieldB))
myObject.FieldB = UpdateFromMethod("FieldB");
if(string.IsNullOrEmpty(myObject.FieldC))
myObject.FieldC = UpdateFromMethod("FieldC");
Is this something that I'll just have to live with, or is there a better way of doing this?
For that specific type of scenario, the only real alternative to ugly repetitive code would be ugly meta-programming code - and at least the current code is readable. If it was just null
you were testing for, null-coalescing (??
) might make it tidier, but fundamentally, the code you have works.
If they really are fields (not properties) you could perhaps do something like:
void Update(ref string value, Func<string> source)
{
if(string.IsNullOrEmpty(value)) value = source();
}
...
Update(ref myObject.FieldA, UpdateFromMethodA);
Update(ref myObject.FieldB, UpdateFromMethodB);
Update(ref myObject.FieldC, UpdateFromMethodC);
but behind the scenes that creates lots of delegate instances that make it undesirable.
Frankly, I'd stick with what you have.
Use reflection.
var type = myObject.GetType();
foreach (var field in type.GetFields())
{
string value = (string)field.GetValue(myObject);
if (string.IsNullOrEmpty(value))
{
UpdateFromMethod(field.Name);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With