Monday, June 23, 2008

Minimalist Code Samples

A minimalist code sample is a snippet that demonstrates a specific purpose, requires no extra context, yet can still run. For example, doFactory.com explains design patterns with a "real-world" sample, and a "structural" (i.e. minimalist) sample. Because it abstracts out the context, the minimalist sample has several benefits:

Easier to apply: It is easier to apply to different contexts - such as new projects.

Easier to remember: It is much smaller (no context means less code), therefore it's easier to remember what the code was about. For example, I have a folder essentially called "LearningSnippets", where I categorize different coding tricks. By keeping all the snippets small, they're fast for me to physically load, "mentally load", and then run. The last thing I want is to dig through some 2000 line project, scratching my head, thinking "how did I do that sorting algorithm?"

Easier to learn: It's easier to learn new concepts. Removing the irrelevant context means there's less to get distracted by, so you can focus on the specific concept that you care about.

Easier to show others: It is easier to show to others, such as a newsgroup, where other developers don't care about the business context. I sigh when I see some poor guy post a 5 page code question on a forum, because few people will sift through all that.

Easier to enhance: It can be much easier to enhance because the code is not constrained by some rigid business context.

It is a courtesy to others: If you just care about a 3-line algorithm, it would be long-winded of me to hide that behind hundred of lines of business context and plumbing.

In .Net, many errors come down to a few bad lines of code - you've got the wrong method, a bad input parameter, or some syntax error. It becomes very convenient when working with others, or learning new concepts, to be able to isolate code down to the minimalist sample.