The smart thing is to practice any code writing one is going to demonstrate in front of an audience. When I was was working in industry and preparing demos for presentations I would typically work though the program code several times before a demo. Over and over until I could get it right in my sleep. As a classroom teacher I sometimes get a bright idea 5 minutes before class starts. And that is where it gets interesting.
The other day I decided that as a class we would work out how to create a program to determine if a string is a Palindrome or not. I’ve done this several times over the years. It’s a great little exercise to practice string handling and loops. Later in the semester we will revisit it as we refactor it into methods. But I was doing it on the fly that day. It went very well. For a while. I kept things very simple.
Then I decided to get fancy which is seldom a good idea. I created an if statement that looked like this:
if (working.Substring(i, 1).CompareTo(working.Substring(working.Length - (i + 1))) != 0)
isPalindrome = false;
It didn’t work. Can you see the problem? I didn’t. My students didn’t. It’s a horrible statement for understanding and debugging. There are just too many pieces all crammed together in one place. Just getting the parentheses balanced took a while. I know better than to write code like this but I was winging it. It wasn’t in my plan at all. So what do you do when demo code doesn’t work? Obviously you pretend it was done on purpose and model debugging methods.
The first step was to make things easier to see via the debugger so I broke the code down a little:
temp = working.Substring(working.Length - (i + 1));
if (working.Substring(i, 1).CompareTo(temp) != 0)
isPalindrome = false;
It’s a lot easier to read and understand already though of course it could be simplified more – and probably should be. If you understand that I want to be comparing single letters you can probably see the error now. The Substring command on the first line is missing the second parameter which specifies how many characters to use. This became immediately obvious when I put the program into the debugger and looked at the values of temp. It wasn’t so obvious in a mash of lots of nested parentheses, parameters inside of parameters and generally to much “stuff” in one statement.
This led to a discussion of simplifying code to make it more readable, more debuggable and more maintainable. We’ll continue the discussion next class. Just don’t tell my students I didn’t do this it on purpose ok?