Brendan Enrick

Daily Software Development

Daily Dev Speedup - Using Visual Studio Snippets

In Visual Studio there are code snippets which can be used with auto-completion. These are a lot of the common structures used by developers when writing code. They are customizable using Visual Studio, but I find it much easier to use editors like Snippy. So if you were not using snippets because one of them was not exactly the way you wanted it to be, give a snippet editor a shot.

I highly recommend creating your own snippets as well as customizing them. I for example use one to create tests. I type 3 letters hit tab and type the name of the test method. This saves me the time of typing the attribute as well as "public void" and some curly braces every time I write a test. Yes, I know that a lot of these are simple little things, but trust me when I say that they all add up into faster development. How do you think all of the visual studio add-ins make money? They allow for a lot of little speed boosts which keep developers coding faster.

Daily Dev Speedup - Working With Words

A lot of applications allow you to work with a group of text at a time. For the purposes of this post I'll call them "words". When I say a lot of applications this includes the powerful IDE called Notepad. This cool trick can be applied in a lot of different places. I am sure you'll figure out some interesting uses for this.

The key (literally) to achieving this productivity from working with words is the Ctrl key. By holding it in combination with other keys we can work with words. The three main things I want to discuss when working with words are: moving from over a word, selecting a word, and deleting a word. As you can probably guess to move through a word you use Ctrl with an arrow key. To select a word you hold Ctrl as well as Shift while using the arrow key. To delete a word you can use Ctrl  in combination with Delete or Backspace. (Yes, I lumped delete and backspace together even though they are technically separate operations.)

Here is a demonstration in Visual Studio showing how to move over words followed by select words followed by deleting words.

Writing Clean Code is a Process

I was copied on an email recently from someone reluctant to begin writing unit tests for code. One of the complaints about the idea of starting late game adding in testing was an interesting one. The person mentioned that because they're starting to test so late that they will not get "all the benefits of TDD". Well, that person is correct. However, that should not stop anyone from making things better.

Recently the "boy scout rule" was brought up to me in the context of coding, and I admit I'd never thought of how well that example applies. The scouts have a rule to leave a camp site cleaner than they found it. This is a great idea since it means that gradually overtime you will be making improvements. No one is saying to go and spend a month cleaning things. That would be a HUGE waste of developer effort from the customer's perspective.

A good rule to live by and one I try to practice regularly is to refactor and clean a little bit every time you touch a file. Even if this just means adding a test or even renaming a bad class, interface, or variable name, the important thing is to make these minor improvements every time you get into some piece of code.

Another complaint about switching was that developers would be spending 50% of their time writing tests. Well I will say that that isn't quite right, but the idea there is accurate. The amount of code written is about half test code and half production code. The advantage of having the tests is less time spent debugging and fixing. Most developers have heard about the cost to fix bugs at different points during the development lifecycle, but I will summarize it as, "the sooner you catch a bug the cheaper it is to fix". If we have tests in place we find the bug sooner. This means the end cost is less, so writing the tests should save us money during development as well as during maintenance.

I admit when I first got introduced to testing I thought a lot of the same stuff. I figured the tests would slow down the development and wouldn't help very much. I figured there would be all these issues, and I'll also admit that it is pretty tough to start doing. Once you start writing tests for things you start to see some of the benefits. The best thing to see is when you change some piece of code and something seemingly unrelated has a test break. That is when you realize the connection and prevent a bug from being created. That is one of the best aspects of testing.

Daily Dev Speedup - Selecting and Dragging Lines

Yesterday I posted about how important it is to use keyboard shortcuts and tools to help you write code faster. Any developer working towards self-improvement should be looking not only into how to program better but also how to program faster.

Today I'll start by mentioning a pretty easy one. If you use Visual Studio I really hope you keep line numbers on. I could probably claim that as the first tip since it does speed things up. This is especially true when collaborating with someone when they can say the line number about which they are speaking. For the real tip I'll be mentioning here you do not need to have the line numbers enabled, but they give you more surface area to click on.

This actually works in a lot of programs, but I'll explain how to use it in Visual Studio. All you need to do is click on the left hand edge of a line and you will be able to select the whole line (this includes the new line at the end). If you click and drag you can select multiple whole lines easily.

Along with this trick you are also able to easily select any text that is highlighted and you can click and drag it to a new location. These work well in combination because rearranging lines becomes very easy. Moving any code at all in fact becomes very easy.

Below is a demonstration of what can be done by clicking and dragging text around and highlighting using the line numbers.

Keeping Code Out of the Code Behind

In ASP.NET development (and yes even in MVC) each page is able to have associated code. This is traditionally (before MVC) how someone would add code to a page. This was much nicer than what was seen a lot on the classic ASP days when a lot of code would be littered between HTML controls.

However, when one is introducing code into the code behind great care must be taken. This is because the code behind is really not the location where most logic goes. If we take a moment to think about what the ".aspx" file is, we will probably come up with something along the lines of, "the file where we decide how we're going to display things to the user." So this is about display issues.

Should it know anything about a database?


Should it know that there is any form of persistent storage?

Probably not.

So what should it know about?

It needs to know how to display things to a user and that is it.

So what do I do once I've got code in the code behind that is business logic?

Step 1 is to try to get it refactored into the correct class. Create new classes to handle the business logic. Your pages will call these classes to do the required work.

If you don't know where to put something yet there is an intermediate step better than having it in the code behind. You can make pseudo-MVC by creating another class. So create a class with the same name as the page but add "Controller" onto the it as a suffix. Then put the logic in there. This will give you a bit of seam which should allow you to test the code.

Keep in mind that the MVC pattern is very cool. ASP.NET is very cool, but it is a fairly old pattern. The idea of it is just separating things. We can do the same thing with ASP.NET if we are careful not to clutter things. We can achieve similar results. Sure it isn't as nice and pretty as MVC, but it gives us seams while separating the concerns of our code so that it is maintainable.

Code Snippets Found Online

One dangerous thing that lot of people have talked about in the past is the danger of getting code snippets online. They're just not trustworthy. Yes, this includes mine. I would like to think that most of mine are good, but I don't have time to carefully check everything I post. I'll make mistakes and include typos sometimes. I attempt to make sure that what I post is accurate and useful, but you should keep in mind that anyone can post on the Internet. There is no restriction, so be careful when taking code snippets and using them. Make sure that you understand what the code does and why it is written the way it is. This understanding will keep you safe when using the code, because you'll be able to identify mistakes before you put them in production code.

One thing that always worries me when I am posting code online is that someone will use my "bad example". I sometimes use an example of the right way and the wrong way. I try to make sure that it is clear which is which, but since I put the bad first, I am worried someone will use it. I have even used the words "bad code do not use this" to describe a snippet which I was pointing out the problems with. I am pretty sure someone has used it though. I admit I've even used the "bad code" from someone's blog before, because the improvement couldn't be made in my circumstances. I did this with some SQL code where I was working with a table instead of a single row as the improvement was.

Be careful when posting or using code from the Internet. If you don't understand something don't use it.

Productive Typing

In software development it is very important that you type quickly. Now some people are going to be thinking that simple words/minute is important. I agree that it is important to be able to type quickly in general while programming. There are other aspects to this as well. Now consider if you have two programmers and one types twice as fast as the other. Which one is more valuable to the company? So I might have oversimplified this, but I would assume most people who go and read blogs are probably trying to improve their skills as a developer and if you're not considering your programming (typing) speed then you're not considering enough.

As a said moments ago, I am not going to talk words per minute. That isn't always relevant since we're not always typing words. Ours are a lot of the same words as well as a lot of symbols. It isn't normal typing. What I am going to say is that developers need to be taking advantage of keyboard shortcuts and snippets; from the standard ones which work in many applications down to Visual Studio specific shortcuts. A lot of developers use add-ins like CodeRush and Resharper to increase their development speed.

Program Agnostic Shortcuts

Starting simply, I will talk about one of the simplest tricks which will help you everywhere. Use your Home and End keys religiously. They will help you tremendously getting you to different points on a line very quickly. This is a simple one that everyone can remember. The extra trick to know here is that you can hold the Ctrl key and it will jump you to the top or bottom of the page.

So I've just mentioned the Ctrl key I will say that it is the most useful key for shortcutting. I'll now go on a rant of the non-VS specific tricks in can help you with.

Everyone should know copy (Ctrl + c), cut (Ctrl + x), and paste (Ctrl + v) There are plenty of other ones dealing with that key that are also very simple. I can't spend the time talking about all of those. Some of the lesser known ones are also important. For example. Everyone knows that you can use the arrow keys to move the cursor right, left, up, and down. If you combine the left-right movement with Ctrl you will notice that the cursor jumps "words". What consists of a word is interpreted differently depending on the application, but try it out in them and you'll see how useful it is. It will save you a lot of time.

Combine this with the shift key for Ctrl +  Shift + [Direction] and you'll be able to select these words very quickly. This is useful for replacing and changing test or simple copying a variable name. Whatever you've got to do. When you're deleting, don't waste time with it. Combing Delete and Backspace with Ctrl will let you delete "words" very quickly.

Visual Studio Specific Shortcuts

I certainly can't cover all of the shortcuts here, but there are a lot of them. For example if you need to make an auto-property all you need to do is be in the context of a class and type "prop" and then hit Tab. You will get a snippet for your property. If you need a for loop you better not waste time writing it. Most for loops are the same, so just type "for" and hit tab. These are all of your snippets and you can customize and create your own. This is easy and there are tools for editing snippets.

You should also look into the different refactorings that Visual Studio is able to do. Right click and choose Refactor from the context menu and you will see a bunch of options available to you.

Also the most powerful shortcut specific to Visual Studio is Ctrl + . which is context sensitive. For example if you change a name pressing that afterward will allow you to do a rename. There are a lot of other context specific options such as including using statements at the top of the file after adding an type which requires one.

Other Tools

If you're really looking to speed up you should look at some of the third party add-ins to visual studio. Resharper and CodeRush are a couple of the popular commercial products. I currently use Resharper, but I've also lost a coding competition to someone using CodeRush. They're great and integrate a lot of what you need. These tools also come with keyboard mapping files which you can print and have a reference of the shortcuts to speed the learning process.

Resharper for example has a lot of shortcuts for navigating. Ctrl + n lets you search for different types and jump directly to them. Ctrl + Shift +  n lets you jump to files. The searching is fairly smart. The tool also adjusts your intellisense so that it pays attention to campital letters. For example if I were going to type "SuperSpecialStaticClass" I could type "SSSC" and that would be the top of my intellisense. If there were a class named "SlightlySpecialStaticClass" I might have to type "SuSSC" or just go down to the next choice in intellisense.

Rather than spend much more time talking about third party tools I will just say that there are a lot of them out there. They're not very expensive and they will make your time spent be more productive.

Make sure you stay up to date on all of the tools and shortcuts available to you.

Something to Avoid While Programming

Some activities and thoughts need to be avoided while programming. Sometimes we realize our mistakes and do them anyway. I admit that in my time developing software I’ve probably done this more times than I would like to admit. I make an effort to avoid making these types mistakes, and I attempt to encourage others to avoid the same pitfalls. While working with others I certainly tell them when they’re gravely mistaken about something.

The first thing I would like to emphasize is that this mistake is fairly common everywhere in life. It is of course procrastination, and I think I’ll rip off the classic line I’ve heard a million times. Don't put off until tomorrow what you could do today. Now I need to be careful how I say this, because I could get YAGNI people jumping at me for saying this. Obviously don’t do everything today just because you can. That is silly, but things that will assist greatly in maintenance should not be put off. Since I’ve been on a bit of a testing kick lately, I might as well focus this toward testing.

I am sure a lot of you have been in the situation where you really just don’t feel like writing your test before you write your code. Ha! Who am I kidding? Most developers don’t follow TDD anyway, so most of the people reading this wouldn’t have done that anyway. A large group of developers have started writing unit tests in general even if they’re not writing them first. However, this still applies as I am sure many of those developers want to wait until a full feature is “complete” before testing.

Your code is not complete until it is tested. Keep in mind that down the road you might forget the business rule you were coding, so it is important to create the tests at the same time as you’re writing the production code. Developers will try to say, “we will write the tests when we’re done” or “we’ll refactor this later”. Do not dare believe a word of that crap. Always assume you will not have time to come back later and refactor. There is a good chance you will not have that chance. Also if you don’t fix things now they’ll just bite you later.

One way to help keep yourself on track is to work with a partner. One very powerful aspect of pair programming is that the second person will nag you and force you to get to things now. That is part of the job description for both parties while pair programming. Don’t let the other person skip out on anything. Be careful though, because that other person will be just like Wimpy saying things like, “I’ll gladly test that Tuesday to continue coding today.”

Writing Testable, Maintainable Code

At our company we’ve had a few interns start this summer, so we ran a little workshop with the development team to help teach the team a few things about writing tests before writing other code. In our test driven workshop we did some simple problems in teams. We looked at different problems from Project Euler, and solved them in pairs. We all worked out our own tested solutions to the problems and brought them back to discuss. While looking at these we discussed what was good in each one and what could have been done better. We were pairing more experienced testers with the new guys for this exercise.

I think this went very well actually. These might not be production level challenges to work, but the variety of designs gives great insight into what people were thinking and how they were approaching the problem. I was delighted to see that there were small bits of code very similar between designs, but overall none of them really looked similar. Class names here and there might have been the same, but the implementations of classes with the same name could vary wildly.

After we finished with the exercise, we jumped back into teams to continue working. A while later I got into a discussion with one of our full-time developers and an intern where I ended up explaining one of the main reasons we like testing code. There is the obvious security of having the tests, but there is more than just that. One added bonus that not everyone seems to realize is that writing testable code creates some interesting properties in the code.

Why don’t we take a look at a few of the properties of testable code. I will certainly not cover all of them, but I will try to get enough to demonstrate my point. (these are in no intentional order)

A Few Properties of Testable Code

  • Keeps dependencies to a minimum – Having fewer dependencies means less mocking, faking, and stubbing.
  • Follows Single Responsibility – This keeps things as small pieces which makes for smaller easier to understand and maintain tests.
  • Programming is done against interfaces – This allows you to mock and fake these objects, because your code only knows about the interface.
  • Dependencies are injected into classes – Without doing this unit testing is impossible and only integration tests could be written.
  • The code is well documented through the tests – The tests themselves describe how the code works, and this documentation stays up to date.

The neat part about this is the fact that these properties are present in maintainable code as well as testable. I'll sit here a moment while that sinks in..... Yes, you heard right that in order for code to be testable it must also be maintainable. If you ask someone how to write maintainable code, they might be able to spout off some information about theoretically how to do it. What is much harder is actually implementing solutions which are maintainable. This is why testing is important, because if you want to even be able to write the tests, the code first needs to be written in nice decoupled, well-organized ways.

I don't know about you, but I think it is very cool when you see that the properties of testable code seem to coincide with best practices for writing maintainable code.

Time-Tested Testing Tips - Part 4

Rather than spending the time with needless introduction, I think I’ll just jump right in today. I’ve got a few tips I am going to post today.

Reproduce Bugs Using Unit Tests

Yes, this is another test driven development method. When you’re looking for a bug, it is very common to try to reproduce it. What you might try to do instead of doing this is reproduce the bug manually, fix the bug, and then write a test to prevent it. Well I think that is a pretty bad way of doing things. Reason number one is DRY; don’t repeat yourself. Why did you reproduce it once manually and once automatically? I also wonder how you know you’ve written the test correctly. If it never failed you can’t be certain you’re testing the bug.

If you write this test first you jump right to finding the bug. Seeing the red of the test failing tells you that you’ve found the bug. Having this test will also let you run the buggy code multiple times, which can be useful if you can’t tell right away what is causing the issue. This becomes a faster, easier process. Since you managed to get the failing test, you know that once you’ve fixed it that you’ve at least fixed the bug you tested. Going the other route you were left to assume that you fixed the bug. We all know what happens when we assume… Yes, that is correct, we are sometimes not accurate.

Keep Dependencies to a Minimum

Yes, this is another situation where we are thinking about both the test code and the production code. If you’re finding that the objects you’re testing are requiring a lot of set up you probably need to simplify things. Get some of these tests in place first. These will help you to clamp down the behavior you want to maintain while you refactor. You’ll want to observe plenty of principles while doing this especially the single responsibility principle.

For example if you have a method which takes in a parameter called BankAccount, but all it really needed was the AccountNumber you should alter your method so it takes the AccountNumber instead. This will make testing easier and it will also lessen your dependence. These are great things to do.

Do not pass an object used to get another. Pass only what is required for something to achieve what it needs to. You need to keep things minimal in this sense. It will make testing as well as maintenance much easier.

Make Things Work Before Making Them Right

It is difficult for a lot of us to follow this, because we know so well how bad some types of code are. We try to avoid having ugly code by spending lots of time and effort trying to get things right the first time. Then we aren’t even sure they work.

Plenty of times in the past, I’ve had programming partners who wanted me to write my code better than I did the first time. Sometimes I made the foolish mistake of listening to them. If you’re dealing with some complicated logic you need to write it the ugliest easiest way you can. This will let you get your tests passing. Once your tests are passing you are free! By knowing that the test and the code are working you have freed yourself up to refactor. You don’t have to think quite so hard since you have this safety net in place. Try something. If it does not work, just revert back and try something else. You will quickly find a design that you like and keeps those tests passing.

Sometimes just seeing the working code will lead you to seeing a better design for it. This situation is much better than if you had spent a lot of time coming up with some way of designing it. The design might not even have worked the first time, and then you would really be wasting time.

I hope you’ve enjoyed these tips. Remember that testing takes a lot of practice. You’ll never see any benefits from testing if you don’t keep writing tests.