Noocyte’s Weblog

August 27, 2009

DRY in the real world

Filed under: Work — Tags: , , — noocyte @ 9:24

In programming there are many, many principles. One of the more useful ones that I’ve discovered lately is DRY: Don’t Repeat Yourself. It’s simple really, never ever copy code and don’t write the same code twice. In the real world it might not be as easy though…

Today I was about to check in some code and I went through my regular check-in routine (you have one as well I presume?) and discovered that I was violating DRY! At least if you’re being anal about it… The code in question was a little like this: (slightly altered to protect the innocents)

   1: using (SPSite site = new SPSite(url)) {

   2:     using (SPWeb web = site.OpenWeb()) {

   3:         lang = web.Language;

   4:     }

   5: }

(I didn’t really return the language, but no need to include all of the source code)

So I was doing the double using in 4-5 places; a clear violation of DRY in my book. So what I did was this:

   1: private T OpenSiteWeb<T>(string url, Func<SPSite, SPWeb, T> implementingMember) {

   2:    using (SPSite site = new SPSite(url)) {

   3:        using (SPWeb web = site.OpenWeb()) {

   4:            return implementingMember(site, web);

   5:        }

   6:    }

   7: }

This method I can use like this:

   1: lang = OpenSiteWeb<uint>(url, (s, w) =>

   2: {

   3:     return w.Language;

   4: }

Pretty neat, no? It might be overkill, but fun code to write anyway!

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Blog at

%d bloggers like this: