Developing with Microsoft technologies
16 Aug 2013

Long lines of code with multiple statements on them are a bad programming practice, right? Well yes, but as with most rules – not always.

E.g. when you insert a code snippet for a data-bindable property with two parameters like this:

compare the reading effort of the generated code for a couple of simple properties when using long lines:

to the same code formatted ‘properly’:

I created the above snippets while I was working on a project to speed up the coding of viewmodels in an MVVM pattern. Creating Visual Studio code snippets is really easy btw – see how.

Generating code with code snippets improves maintainability when writing new code – you only need to enter a few snippet parameters, say one statement worth of input, and many statements can be generated for you on the fly. Great for automating small, repetitive coding patterns.

However, the amount of time spent on writing versus reading code is in the order of 1 : 10. So if you generate 5 lines of code from entering the equivalent of 1 line of code, you only reduced the amount of time spent on that code by 8%. To improve that, you can hide part of the code – you really only need to consciously see the part of the code that you edited when you invoked the code snippet.

I first considered regions to hide code, but that requires you to collapse the region for each property, or for the entire file, which is not always what you want to do. It also requires three lines for each property instead of one:

So instead I opted to use a long inline comment followed by all code on one line, to hide the extra code ‘in plain sight’. After you have examined the code after the comment once, your eyes start to ignore the code after the green ‘comment curtain’ automatically – even more so with blocks of snippet instances. The comment also tells you which code snippet was used, so others can continue coding in the same pattern.

Here is part of a real-life viewmodel with different snippets used:

As you can see, one snippet can generate multiple lines, with each line showing only the part that you need to know about:

Happy coding!

About the Author
Vincent Hoogendoorn is a hands-on .NET architect and a Xamarin cross-platform mobile veteran, working as lead mobile @ Workstreampeople. His areas of interest are Augmented Reality, Cross-Platform Mobile Development, Windows Azure, Solution Architecture and Software Factories.

Leave a Reply


captcha *