Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More elegant way of updating empty object properties

Tags:

c#

oop

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?

like image 416
MrC Avatar asked Mar 21 '23 03:03

MrC


2 Answers

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.

like image 89
Marc Gravell Avatar answered Apr 01 '23 05:04

Marc Gravell


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);
    }
}
like image 28
rareyesdev Avatar answered Apr 01 '23 06:04

rareyesdev