What is a good design pattern for dealing with complex classes that have potential null sub classes?

StackOverflow https://stackoverflow.com/questions/23567653

  •  19-07-2023
  •  | 
  •  

Question

I am using Entity Framework Model First to create a data access layer. In my MVC project I am using this DAL to retrieve a complex object from my DB.

var street2 = Person.Address.Street2;

What I am trying to determine is what pattern or process I should be using to handle potential situations where Street2 or even Address doesn't have a record in the DB.

I know I could test for null objects at the point where I am using them but I was wondering if there is a pattern or method that would remove the need to do that at such a fine grained level. i.e.

if(Person.Address!=null && Person.Address.Street2!=null)
{
var street2 = Person.Address.Street2;
}

Until we get a Safe Navigation Operator is there another good pattern to use?

Would it make sense to create a getter in the classes to check for null objects and if there is create a new empty object and return that?

Am I making this more complex then it needs to be?

Any thoughts on AutoMapper and it's null substitution?

Was it helpful?

Solution

No. That's the way you've to do it. You've to do it the way you're doing.

However use short circuit in your if conditions to increase performance

OTHER TIPS

You could create object validators and use Decorator pattern this would work for updates and such, you still manually would have to check for nulls in places where logic demands.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top