Agile Zone is brought to you in partnership with:

Mark is a graph advocate and field engineer for Neo Technology, the company behind the Neo4j graph database. As a field engineer, Mark helps customers embrace graph data and Neo4j building sophisticated solutions to challenging data problems. When he's not with customers Mark is a developer on Neo4j and writes his experiences of being a graphista on a popular blog at http://markhneedham.com/blog. He tweets at @markhneedham. Mark is a DZone MVB and is not an employee of DZone and has posted 516 posts at DZone. You can read more from them at their website. View Full User Profile

TDD, small steps and no need for comments

07.23.2010
| 6301 views |
  • submit to reddit

I recently came a blog post written by Matt Ward describing some habits to make you a better coder and while he presented a lot of good ideas I found myself disagreeing with his 2nd tip:

2. Write Your Logic through Comments

When it comes to coding, there are many tenets and ideas I stand by. One of this is that code is 95% logic. Another is that logic doesn’t change when translated from human language into a programming language.

What this means is that if you can write it in code, you can write it in a spoken language like English or French.

Instead of just jumping into coding the function, I could step back and write the logic in plain English as comments.


I've tried this approach before and although it can be useful I found that quite frequently I ended up with a more complicated solution than if I'd driven it out with a test first approach.

The advantage of driving the code from examples/tests is that it helps to put you in a mindset where you only need to care about one specific way that a particular object may be used.

As a result we often end up with simpler code than if we'd tried to imagine the whole design of that object up front.

I find it more difficult to keep a lot of code in my head but having just one example is relatively easy. The less code I have to think about at any one time the less mistakes I make.

As we add additional examples which describe different ways that the object may be used I've often found that the code ends up becoming more generalised and we end up with a simpler solution than we might have imagined when we started.

Matt goes on to say:

This way, I can think through the full logic and try to iron out the wrinkles before I actually get into writing the code. I’ve found this to be an incredibly valuable habit that tends to result in fewer bugs.


Using a TDD approach "allows us to describe in code what we want to achieve before we consider how" so the examples that we write provide an executable specification of what we expect the code to do.

I don't have a problem with making mistakes when coding. I make mistakes all the time but having the safety net of tests helps me fix them pretty quickly.

Matt ends this section with the following:

As a bonus, since I will rarely actually delete the comments, writing the logic through comments also means that my code will already be documented, making it easier for others to follow my logic if they ever have to work on it, or even just for myself, if I have to come back to it several months or years down the road!


There are other ways of documenting code which don't involve peppering it with comments. We can write our code in a way that reveals intent such that instead of having this:

// FUNCTION: Lock On Time
// This function will accept two time values, indicating the range through
// which it should return an unlocked status.

// Create a new data object

// Using the data object, get the current time

// IF the current time falls within the range passed to the function

// Return false – meaning that we are currently unlocked

// ELSE

// Return true – meaning that we are currently locked.

// ENDIF

// END FUNCTION

We have something closer to this:

public bool ShouldBeLockedBasedOn(DateTime startOfTimeRange, DateTime endOfTimeRange)
{
var dataObject = CreateDataObject();
var currentTime = dataObject.CurrentTime;

if(currentTime.IsBetween(startOfTimeRange, endOfTimeRange)
{
return false;
}
return true;
}

…where 'IsBetween' would be an extension method on DateTime. We could have that as a private method but I think it reads better this way.

Comments don't tend to be maintained in the same way that code is from my experience so as soon as the code around them changes we'll find that they quickly become misleading rather than helpful.

There are certainly times when it makes sense to put comments in code but using them as a substitute for writing intention revealing code isn't one of those!




References
Published at DZone with permission of Mark Needham, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Philopator Ptolemy replied on Fri, 2010/07/23 - 8:27am

Writing your code "through" comments is a technique well known as pseudocode programming.

The best computer programming book of all times - Code Complete 2nd edition has this:

The term "pseudocode" refers to an informal, English-like notation for describing how an algorithm, a routine, a class, or a program will work. The Pseudocode Programming Process defines a specific approach to using pseudocode to streamline the creation of code within routines.

  • Use English-like statements that precisely describe specific operations.

  • Avoid syntactic elements from the target programming language. Pseudocode allows you to design at a slightly higher level than the code itself. When you use programming-language constructs, you sink to a lower level, eliminating the main benefit of design at a higher level, and you saddle yourself with unnecessary syntactic restrictions.

  • Write pseudocode at the level of intent. Describe the meaning of the approach rather than how the approach will be implemented in the target language.

 

Personally, i also find it extremely useful and less inconvenient than TDD.
After all TDD requires writing actual code that needs to be both precise and syntactically detailed which takes more time. Furthermore, when the logic changes, the tests need to change just like the comments do.

Ronald Miura replied on Fri, 2010/07/23 - 9:47am in response to: Philopator Ptolemy

Comment-Driven Design? Probably a really good idea if you use a programming language that don't allow you use the right level of abstraction for the code represent intent itself (assembly comes to mind. No, Java doesn't fall in this category, you Ruby fanboys :P). Even with modern languages it may be a good way to design, if it fits your way of thinking. I don't buy this idea people try to sell that TDD is the only way to design good software. There are many different techniques, and which is best will depend on a number of factors (what problem you want to solve, the designer's thinking process, the level of the code you are designing, etc.).

Ronald Miura replied on Fri, 2010/07/23 - 10:17am

What about writing the comments to help you to think about the algorithm, and erase them while you code the steps (using TDD, or not)? I've done this some times. In my case, they worked as placeholders, remembering me what to do next. Of course, the comments are very high-level ('//calculate total', '//retrieve list of itens'), and each line would probably turn into a method call. Comments like '// create new object', or '// set i to 0' are stupid.

Loren Kratzke replied on Fri, 2010/07/23 - 12:23pm in response to: Ronald Miura

Agreed. Experience tells me that a good programmer needs to use every tool in the box. Tests in development are a gross misuse of a good tool intended to maintain code integrity and function over time. (like hammering a nail with a screwdirver). To me, TDD is little more than a fad - hardly a solution to anything, let alone everything.

I think that some great programmers will emerge from this period of TDD insanity and look back someday and just shake their heads. They will be wiser for having believed for a period of time that TDD was the be all and end all of design, and then eventually learned otherwise.

Personally, I am a big fan of DDD (Design-Driven Design). At this rate it will seem like a brand new concept before long. I will write a book, start a consulting company specializing in introducing it to companies and training them in this new concept, and then retire as a very wealthy, healthy, and happy man.

Philopator Ptolemy replied on Fri, 2010/07/23 - 12:56pm in response to: Ronald Miura

Comment-Driven Design? Probably a really good idea if you use a programming language that don't allow you use the right level of abstraction for the code represent intent itself (assembly comes to mind. No, Java doesn't fall in this category

IMHO, a language that includes constructs like loops for example can use a higher level of abstraction to express intent of the loop - i.e. something like find max in the array. Arguably languages like Ruby/Groovy are more expressive in that area but there is always higher level of abstraction that can be useful in conveying intent of the code.

The only reservation, or more correctly specialization of this technique, that i have been employing in the last few years is to convert comment into name of a newly extracted small function. This allows to read the code at the level of intent and to maintain consistent level of details and abstraction (key principal in writing intelligible code).

Allan Howward replied on Tue, 2011/09/20 - 1:09pm

Translating a business statement into technical language can be a difficult job and one should respect that difficulty. -Julia Timonina

Emma Watson replied on Fri, 2012/03/30 - 5:55am

In my experience, code comments might be useful to rapidly think through a solution, especially a more "algorithmic" one. Nevertheless, I'm completely in favor of not using code comments in the final code, except for possibly documenting the public interface (though in this case the test suites could be a far better way of doing this) or to explain complex pieces of code. I read somewhere that "code comments are deodorant for poorly written code".

Swing

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.