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:
1: private double CtoF(double x)
2: {
3: return x * 9.0 / 5.0 + 32;
4: }
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.
In the Java text I am using (Lewis & Loftus) they do these extremely simple methods all the time. Methods that are one liners like in your example. I asked the exact same question your students are asking "why?" of the university prof who is helping me with the course. He said most of them are for demonstration purposes. Without his comment I would say what a way to make life confusing with all the extra methods. What helped was when we started talking about libraries and the math methods. When someone does not explain the "why" it can make absolutely no sense.
ReplyDelete