Students ask interesting questions. One of the more frequent questions they ask is “why would you do that?” Often it comes, not because you didn’t already explain why one would do something, but because the answer doesn’t really register in the abstract. For example we are spending some time on creating methods (subroutines/functions) in our programming class. When I introduced them as a concept I explained multiple reasons why we use them. Simplification, ease of testing, reuse, etc. Then we worked on how they are created and used. As is typical I started with something very simple. Perhaps too simple? In any case what we did was to break out some equations (temperature conversions) and put them in their own methods.
The methods are very simple. Sometime like this:
My goal of course is to explain the mechanics of setting up and calling a method. So a method with very simple code in it seemed like a good idea. And then the dreaded question “why would you want to do that?” This actually adds some complexity to the code in some ways. It feels like extra work and it is hard to argue that it is not.
The discussion was now open though and that was a plus. I asked the student if they’d like to write code to replace the ToString method. Of course he said yes and it working on it but most of the class is fine reusing the existing method. Having done some string and char manipulation the students have some ideas about what is involved. Asking them if they would want all that code in their program everywhere they currently call the method makes the value of methods start to sink in.
It will become even more evident when we start writing our own classes in the near future. But I have a feeling that at some point, probably when talking about data hiding and using methods to access class data I will once again hear someone say “why would you do that?” No matter how many times I have already tried to answer the question in advance.