Code snippets and reuse

May 04, 2009

Jeff Atwood recently wrote about copy and paste coding, and those small, frequently reused code snippets that pop up at every programming blog or website.

To me, the most troubling limitation of copypasta programming is the complete disconnect between the code you've pasted and all the other viral copies of it on the web. It's impossible to locate new versions of the snippet, or fold your features and bugfixes back into the original snippet. Nor can you possibly hope to find all the other nooks and crannies of code all over the world this snippet has crept into. What I propose is this:
// codesnippet:1c125546-b87c-49ff-8130-a24a3deda659
- (void)fadeOutWindow:(NSWindow*)window
        // code
Attach a one line comment convention with a new GUID to any code snippet you publish on the web. This ties the snippet of code to its author and any subsequent clones.

I’ve been idly thinking about the same thing lately, especially since I’ve started using services like gist.github to share and view small code snippets. A good example is a category on NSBezierPath to add rounded rectangles, which I remember copying from someone 5 or 6 years ago when I first started with Cocoa. If I was using this in a project today there’s no way I would remember who it originally came from, or be able to tell (except accidentally) that Leopard added the same thing when it was released and now I don’t need to use the snippet at all.

I really don’t know if GUIDs are the best (or even a workable) solution. I don’t have anything against the idea, but how can you enforce it on every blog, code sharing website, programming forum, and so on? Still, when I think about a programmer’s dream world I imagine my IDE tagging these snippets with contextual information, popping up a window with text from a blog post just like it does with autocompletion.

Marc Charbonneau is a mobile software engineer in Portland, OR. Want to reply to this article? Get in touch on Twitter @mbcharbonneau.