Today, Peter Kofler and I have been pairing over the Internet to do deliberate practice. To improve our coding skills. We have been working on the word wrap kata, to practise the Transformation Priority Premise, this time using JavaScript. We’ve checked-in the code after every little change so the evolution can be seen in the “commits” in the repo.
What I have learned in this session:
- I will always use curly braces in “if” statements even when they only contain a “return” statement: I used to think that, even without the braces, developers would notice the “return” and thus avoid the mistake of adding lines afterwards. But Peter suggested that some developers might add lines before the “return” statement. This is something I didn’t think of before!
- Code symmetry helps to explain the intention of the code.
Code symmetry started to grab my attention when I saw Kent Beck in his TDD screencasts. In the second episode he prefers to leave some duplication in favor of symmetry.
Peter and I were working on a simple function to find out the position where we had to wrap the line. We had a green test with this implementation:
function wrapPosition(paragraph, maxLineLen){
if (paragraph.indexOf(" ") > -1){
return paragraph.indexOf(" ");
} else {
return maxLineLen;
}
}
Then I noticed that the “else” was not necessary so I removed it:
function wrapPosition(paragraph, maxLineLen){
if (paragraph.indexOf(" ") > -1){
return paragraph.indexOf(" ");
}
return maxLineLen;
}
The Peter said, “now the ‘if’ statement looks like a guard clause, but in reality we don’t have such a guard clause”.
This is true, the reader may wonder why is that guard clause in there. Actually we know that any of
the two paths is possible, so the “else” expresses the intent of the code better.
But we still thought that the “else” was not necessary, so Peter came up with the idea of inverting the condition:
var lineBreak = "\n";
var notFound = -1;
function wrapPosition(paragraph, maxLineLen){
var hasNoBlank = paragraph.indexOf(" ") == notFound;
if (hasNoBlank){
return maxLineLen;
}
return paragraph.indexOf(" ");
}
Now it does not look that much like a guard clause. What do you think?
Some related talks and posts that Peter has sent to me, related to our discussion today:
- http://blog.code-cop.org/2011/08/word-wrap-kata-variants.html
- https://vimeo.com/57851350 – Micah Martin
- https://vimeo.com/59265614 – Micah Martin
- http://blog.8thlight.com/micah-martin/2012/11/17/transformation-priority-premise-applied.html
- https://www.youtube.com/watch?v=A64Z8vMd6Q8&feature=youtu.be – Kent Beck on coaching programmers
It’s been a very interesting discussion, I want to say thank you to Peter for arranging this session. There will be more soon 🙂