Check for null or empty fields in an entity without consecutive use of "if-else"

2

In an integration between systems there are data updates on both sides, where the A-side record and the B-side record are obtained. If there are null fields in A and these exist in B then A is complemented with B the reverse is also true, it's like a merge between records. To solve this question I tried two ways that worked, but at least for me, it is "gambiarrado".

1st Approach - Reflection

foreach (var propertyInfo in entidadeA.GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
    var valor = propertyInfo.GetValue(entidadeA, null);
    camposNull.Add(nameof(propertyInfo.Name))
}

2nd Approach - Verification on entity instantiation

public class EntidadeA{
    private string _campoA {get; set;}
    public  string CampoA 
    {
      get { return _campoA; }
      set 
      { 
         _campoA = value;
         if(string.IsNullOrEmpty(value))
            camposNull.Add(nameof(CampoA))
      }
}

Entities have more than 20 fields, so my goal is to reduce as much as possible from if-else . Is there any other way to do this? The second form, if the entity is used in a serialization for JSON or XML could generate problems?

    
asked by anonymous 06.10.2017 / 16:00

1 answer

1

There is always another way. The question is whether it is suitable for present need and will be for others that may arise. You need to do something that is conceptually correct.

I do not see problems in the second way. A serialization will call get and receive the result.

This camposNull in the class is seeming to me to be gambiarra, no matter how populated, but it can be correct, I have no more information to affirm.

Stranger is a property that uses another property as a field. It may, but I do not know if it is the intention.

I would avoid reflection, in fact, whenever I can. The performance is poor and opens up cracks for even security code failures. When it's needed it's a great tool, but I would not abuse it. In languages like C # you need to automate something you prefer code generation or do in hand.

    
06.10.2017 / 16:13