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!

May 23, 2008

Microsoft Source Analysis releases to web

Filed under: Link — Tags: — noocyte @ 22:04

Pretty cool tool! I’ve been thinking about starting a blog called “Code Nazi”, and this tool is just up my alley! 🙂 Will test real soon!

Microsoft Source Analysis releases to web

Blog at