Why code snippets promote bad design

It is a well established guideline that duplicate code should be prevented. It’s one of the main software design principles, also known as “Don’t Repeat Yourself” (DRY).

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system. – Andy Hunt and Dave Thomas in their book The Pragmatic Programmer

Code snippets are defined as “a small region of re-usable source-code“. A lot of IDE’s have a feature to manage and use code snippets. It should be quite obvious why this contradicts DRY. It is actually even worse, as it makes it easier for you to do so. Yet, so many people embrace them as a good ‘solution’. There already exists a solution for having to write duplicate code, it is called encapsulation.

So why do code snippets exist? Sometimes you reach the limitations of a programming language, and a piece of code can’t be encapsulated any further. You want to do a similar task over and over again, but with variable parameters. A good example of this is a C# property, which defines a value, accessible through a getter and optionally a setter.

public string Name

The previous sample is an auto-implemented property. Every keyword is relevant and required by C#. An equivalent would be a simple member field, “public string Name;“, but this wouldn’t give us the flexibility to easily make the setter private, or add additional code to the getter or the setter. The point I’m making is, within the confines of the language, it can’t be simplified without sacrificing flexibility. This should be the only reason to use code snippets!

Personally, I don’t use snippets at all, as I spend way more time designing my code, than writing it anyhow. Furthermore, I see the following disadvantages when using them:

  • You think less about the code you are writing. E.g. for the property, by default the setter is public, which is definitely not always desirable.
  • It promotes laziness, not caring whether a certain snippet can be encapsulated. E.g. code snippets for dependency properties as I discussed earlier.

Even when you find yourself in a scenario where you write a lot of code which can’t be improved any further, other options are available, e.g. code generation. I might make this the subject of one of my future posts.

About these ads
  1. Leave a comment

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s


Get every new post delivered to your Inbox.

%d bloggers like this: