When teaching beginners how to program there are a whole cast of variables to deal with. One of them is finding learning projects or exercises that are complicated enough to be interesting but simple enough that students can work them out in a reasonable time frame without being burdened by trying to understand and use too many new concepts at once. Exercises that are too artificial bore students and demotivate them. Exercises that are to complex frustrate students. It can be a fine line. I ran into this teaching class creation and use in my C# course this week.
I used a Dice class to demonstrate how to build a class. I love the Dice class because it meets all my requirements. Students tend to be interested in dice and random numbers in general. Of course they also understand dice so discussion around what the features and functions of a Dice class are comfortable for most everyone. The class lends itself to covering all the basics:
- Two constructors – a default and one that lets the number of sides be specified.
- A method that just changes a value – roll to set the value of the die
- A property, Value, that can be returned but not directly modified from outside the class
- A reasonable and pretty obvious ToString method to make to return a text value of the dice for display purposes.
The code is quick and easy to write as well. I’ve used this as a demo for years. But what is the follow on? What do I have the students write on their own? This week I have decided on a magic 8 Ball class. It’s a little more complicated than the dice class in that it uses an array to hold the various messages but I think that is a good thing.
They’ll still have two constructors. One that uses a pre-populated array of messages and one that accepts a user supplied array of messages. Let’s me remind them about passing arrays which is also useful. There will be a Shake method to change the current message and a ToString to return the current message. We’ll see if they come up with other methods on their own.
We’ve talked some about how you could incorporate this sort of code in a main program but why it might be better to do it as a class. My plan is to work up to some more complicated classes where the value of a separate class is even more obvious. This should help with design discussions and with reinforcing the value of breaking big problems into multiple smaller, simpler problems. It should also help when we move back into some of the larger case study style projects I’ve been having them work with.
I’ve having fun with this. I hope the students are as well. Learning should be fun.