Commenting for Clarity

Often we re told to comment our code to make it more clear. I think just for fun, I ll comment this code to show where these ideas are hiding. We ll see whether this makes the code better. Then we ll see whether we can do better than just putting comments in to make things more clear.

// Handle the Enter Key
public void Enter() {
// On Enter, we change the TextModel lines to insert, after the line
// containing the cursor, a blank line, and a line with < P >< /P > . We set the new
// cursor location to be between the P tags: < P > < /P > .
// calculate which line has the cursor
int cursorLine = CursorLine();
// allocate a new line array with two more lines
String[] newlines = new String[lines.Length+2];
// copy line 0 through cursor line to output
for(int i = 0; i <= cursorLine; i++) {
newlines[i] = lines[i];
// insert blank line
newlines[cursorLine+1] = "";
// insert P tag line
newlines[cursorLine+2] = "<P></P>";
// copy lines after cursor lein to output
for (int i = cursorLine+1; i < lines.Length; i++) {
newlines[i+2] = lines[i];
// save new lines as result
lines = newlines;
// set cursor location
selectionStart = NewSelectionStart(cursorLine + 2);

If your eyes are sharp, you noticed a typo in (at least) one of those comments. I noticed that while typing it in but decided to leave it to remind us all that I might not have noticed it. Comments aren t checked by the compiler, and they don t have to reflect reality. However ”and you ll have to take my word for this ” I did rebuild the program and run the tests after putting these comments in, and it did compile and run even with that mistake in the comment. <smile/>


This is a message from the Ron Jeffries of the future. You should know something that the Ron Jeffries writing this chapter does not: The tests he is running don t test the TextModel at all; the only tests for it are currently manual. The manual tests do run, but he has been very lucky! Watch what happens!

Is This Really More Clear?

In addition, we need to ask ourselves whether this is better code. Frankly, I d rather deal with this method in its first form rather than the second. Your mileage may vary on that. But let s see where we wind up before we finally decide.

Extreme Programming Adventures in C#
Javaв„ў EE 5 Tutorial, The (3rd Edition)
ISBN: 735619492
EAN: 2147483647
Year: 2006
Pages: 291

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: