Editorials

Writing Perfect Code

I recently read a blog about coding style. The premise was that simpler code is better. For example, if you could write a line of code using a lambda expression, it would be better than writing three lines of code using traditional coding techniques.

If I were to use that same reasoning, I would be able to say, writing a Linq statement in Dot Net would be better than writing a FOR Loop using traditional set techniques. When using Resharper while writing C# code, it often prompts me to replace FOR Loops with Linq queries, following this same principle.

Perhaps these are two different things. For example, if I create a delegate, I can use different lambda expressions when implementing the delegate, opposed to creating complete methods with names and signatures, melding the delegate implementation with the method implementation. From that perspective, I can see the value of simplicity. I don’t have to find the method somewhere, when implementing the delegate, in order to see what is going on. It’s all right there in one place.

I do find this method more difficult to follow, and debug, when using parallel FOR Loops. Generally, you use some sort of lambda expression in the parallel FOR Loop to define the body of what is being executed. In that case, I prefer to have as little in the lambda expression as possible, and put the majority of the work in a called method. That way I can create break points on individual lines of the work. If you put everything inside the body of the lambda expression, in Visual Studio, it breaks on the entire body of work, instead of individual statements.

I also find I can unit test a method, and then call it within a lambda statement. While I can’t unit test a lambda statement embedded within a Parallel For as easily.That being the case, I would contend that it is more important to be able to test code, than to keep it short. The two are not mutually exclusive. But, I would give up short syntax before complicating testing.

What would you say the goal is when writing code? Share your opinion by leaving a comment.

Cheers,

Ben