Thursday, November 1, 2012

10 steps to becoming a better programmer

Hi and welcome back to my blog!
I wanted to cover 10 of the things I’ve learned over the years being a professional programmer that really helped me improve the quality of my code and my overall productivity.

1. Never ever duplicate code

Avoid duplicating code at all costs. If you have a common code segment used in a few different places, refactor it out into its own function. Code duplication causes confusion among your colleagues reading your code, it causes bugs down the line when the duplicated segment is fixed in one location and not the others and it bloats the size of your code-base and executable. With modern languages its become possible to get really good at this, for example here is a pattern that used to be hard to solve before delegates and lambdas came along:
/// <summary>
/// Some function with partially duplicated code
/// </summary>
void OriginalA()
{
 DoThingsA();
 
 // unique code
 
 DoThingsB();
}
 
/// <summary>
/// Another function with partially duplicated code
/// </summary>
void OriginalB()
{
 DoThingsA();
 
 // unique code
 
 DoThingsB();
}
But now we can refactor the shared part of both functions and rewrite using a delegate:
/// <summary>
/// Encapsulate shared functionality
/// </summary>
/// <param name="action">User defined action</param>
void UniqueWrapper(Action action)
{
 DoThingsA();
 
 action();
 
 DoThingsB();
}
 
/// <summary>
/// New implmentation of A
/// </summary>
void NewA()
{
 UniqueWrapper(() =>
 {
  // unique code
 });
}
 
/// <summary>
/// New implementation of B
/// </summary>
void NewB()
{
 UniqueWrapper(() =>
 {
  // unique code
 });
}

2. Notice when you start distracting yourself

When you find yourself flicking to facebook or twitter instead of working on a problem its often a sign that you need to take a short break. Go grab a coffee away from your desk and talk to your colleagues for 5 minutes or so. Even though this seems counter intuitive, you will be more productive in the long run.

3. Don’t rush the solution out the door

When under pressure to produce a solution to a problem, or to fix a bug, its very easy to get carried away and find yourself rushing, or even missing out your usual crucial testing cycle completely. This can often result in more problems and will make you look less professional in the eyes of your boss and colleagues.

4. Test your finished code

You know what your code is supposed to do, and you’ve likely tested that it works, but you really need to prove it. Analyse all the potential edge cases and make a test which confirms that your code performs as expected under all possible conditions. If there are parameters, send values outside of the expected range. Send null values. If you can, show your code to a colleague and ask them to break it. Unit testing is a formalised approach to this.

5. Code review

[...]
Read more: 10 steps to becoming a better programmer

No comments:

Post a Comment