user1295450
user1295450

Reputation: 167

C# Best practices in object initialization

I have an Order object and the Order object contains a Person object which stores the information about the person who placed the order. When I populate the Order object am I supposed to populate the Person object as well? Or would I be better off calling order.GetPerson() whenever I need to access to the person who placed the order.

Upvotes: 0

Views: 687

Answers (3)

C B
C B

Reputation: 647

As the comment by Chris Sinclair indicates, it does come down to your design and considering how frequently you'll need the Person objects. If nearly every time you load Orders, you want the associated Persons as well (for display, or calculations, etc.) then it makes sense to always load the Persons to limit the number of database calls. If you hardly ever need the Person data, then it makes more sense to get the Person data in a late-bound/lazy-loading manner.

Consider this example. You retrieve all orders to display them in a grid. But when you populate the grid, you also want to display the Person info per order. If you load the Person data with each Order, you just loop the Orders and you have no more database calls. If you use lazy-loading of the Person data instead, then as you loop the orders you have to make an additional database call per Order to get the Person data. That's a lot of calls.

If appropriate, you could also split the difference and design load methods to which you can pass a flag of "LoadChildren." Doing so gives you the ultimate flexibility, but maintainability/readability is sacrificed because depending on where you are in code, you won't necessarily know if the Person data is populated or not.

Upvotes: 0

derGral
derGral

Reputation: 1856

If resources are an issue then Shyju's answer makes sense. Otherwise, if you always know the person that's associated with the Order then, yes, populate it. Also, it's a good idea to make objects immutable as often as possible, and you probably can in this case; i.e. pass the person in through the constructor and never change it.

Upvotes: 0

Shyju
Shyju

Reputation: 218702

You may consider the LazyLoading approach. So that the Person data will be fetched and loaded when it is required (queried for the first time)

Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed

Upvotes: 2

Related Questions