15.01.2013 Views

Foundations of Programming - Karl Seguin

Foundations of Programming - Karl Seguin

Foundations of Programming - Karl Seguin

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 9 - Back to Basics: Proxy This and Proxy That<br />

Interception<br />

The reason we're exploring a more technical side <strong>of</strong> inheritance is because two <strong>of</strong> the tools we've l ooked<br />

at so far, RhinoMocks and NHibernate, make extensive use <strong>of</strong> proxies - even though you might not have<br />

noticed. RhinoMocks uses proxies to support its core record/playback functionality. NHibernate relies on<br />

proxies for its optional lazy-loading capabilities. We'll only look at NHibernate, since it's easier to<br />

understand what's going on behind the covers, but the same high level pattern applies to RhinoMocks.<br />

(A side note about NHibernate. It's considered a frictionless or transparent O/R mapper because it<br />

doesn't require you to modify your domain classes in order to work. However, if you want to enable lazy<br />

loading, all members must be virtual. This is still considered frictionless/transparent since you aren't<br />

adding NHibernate specific elements to your classes - such as inheriting from an NHibernate base class<br />

or sprinkling NHibernate attributes everywhere.)<br />

Using NHibernate there are two distinct opportunities to leverage lazy loading. The first, and most<br />

obvious, is when loading child collections. For example, you may not want to load all <strong>of</strong> a Model's<br />

Upgrades until they are actually needed. Here's what your mapping file might look like:<br />

<br />

<br />

<br />

<br />

...<br />

<br />

<br />

<br />

<br />

<br />

By setting the lazy attribute to true on our bag element, we are telling NHibernate to lazily load the<br />

Upgrades collection. NHibernate can easily do this since it returns its own collection types (which all<br />

implement standard interfaces, such as IList, so to you, it's transparent).<br />

The second, and far more interesting, usage <strong>of</strong> lazy loading is for individual domain objects. The general<br />

idea is that sometimes you'll want whole objects to be lazily initialized. Why? Well, say that a sale has<br />

just been made. Sales are associated with both a sales person and a car model:<br />

Sale sale = new Sale();<br />

sale.SalesPerson = session.Get(1);<br />

sale.Model = session.Get(2);<br />

sale.Price = 25000;<br />

session.Save(sale);<br />

<strong>Foundations</strong> <strong>of</strong> <strong>Programming</strong> Copyright © <strong>Karl</strong> <strong>Seguin</strong> www.codebetter.com<br />

75

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!