Raj Rao
Raj Rao

Reputation: 9138

Complex objects design: so as to not have to retrieve the entire object graph

Not sure what the best title would be for this question, or even if I am being clear, but here it is:

What is the best way to setup complex objects so as to not have to retrieve the entire object graph when the parent object is first being accessed?

For example: Order

Would you create the Order with all its dependent objects as properties or would you provide accessor method for the dependent objects?

example:

Option 1:

class Order

Option 2:

class Order

- public GetCustomer():Customer

- public GetOrderLines():List of order lines

The way I see it each has its own advantages and disadvantages:

Option 1: Class diagrams show the relationship between different objects. The disadvantage is that when you are getting the Order object, you need to get the entire object graph (which could get expensive and in many cases might be unnecessary).

Option 2: Because each object is retrieved through a Get call, you can defer the actual retrieval to when the object is needed. Disadvantage, at least in Visual Studio class diagrams, you can no longer get nice relationships between the different objects.

Are there any other design patterns that can accomplish what I am trying more efficiently?

Upvotes: 0

Views: 270

Answers (2)

guillaume31
guillaume31

Reputation: 14064

The choices of Property vs getter method and lazy loading vs full object graph are orthogonal, you can pretty much have any combination of them.

I'd probably choose a Property here since it's more idiomatic to C#. As for deferring the object retrieval, it depends on your context - like anon wrote, when drawing from database data lazy loading can be appreciable.

Upvotes: 2

anon
anon

Reputation: 4618

Would you consider using an ORM such as Entity Framework or NHibernate? That way, you'll get Lazy Loading support without having to go through a lot of trouble implementing it yourself.

Upvotes: 4

Related Questions