TITLE: More Serendipity
AUTHOR: Eugene Wallingford
DATE: November 17, 2006 4:36 PM
When my CS1 class and I
recently, it occurred to one student that we might be able
to compress our images, too. Pictures are composed
of Pixels, which encode RGB values for colors. We
had spent many weeks accessing the color components using
accessors getRed(), getGreen(), and
getBlue(), retrieving integer values. But the
color component values lie in the range [0..255], which
would fit in byte variables.
So I spent a few minutes in class letting students implement
compression and decompression of Pixels using one
int to hold the three bytes of data. It
gave us a good set of in-class exercises to practice on, and
let students think about compression some more.
The we took a peek at how Pixels are encoded -- and
found, much to the surprise of some, that the code for our
text already uses our compressed encoding! We had reinvented
the existing implementation.
I didn't mind this at all; it was a nice experience. First,
it helped students to see very clearly that there does
not have to be a one-to-one relationship
between accessors and instance variables. getRed(),
getGreen(), and getBlue() do not retrieve
the values of separate variables, but rather the corresponding
bytes in a single integer. This point, that IVs != accessors,
is one I like to stress when we begin to talk about class design.
Indeed, unlike many CS1 instructors, I make a habit of creating
accessors only when they are necessary to meet the requirements
of a task. Objects are about behavior, not state,
and I fear that accessors-by-default gives a wrong impression
to students. I wonder if this is an unnecessary abstraction
that I introduce too early in my courses, but if so then it
is just one of my faults. If not, then this was a great way
to experience the idea that objects provide services and
encapsulate data representation.
Second, this gave my students a chance to do a little bit
arithmetic, figuring out how to use multiplication to move
values into higher-order bytes of an integer. Then we looked
inside the Pixel class, we got to see the use of
Java's shift operators to accomplish the same goal. This
was a convenient way to see a little extra Java without
having to make a big fuss about motivating it. Our context
provided all the motivation we needed.
I hope the students enjoyed this as much as I did. I'll have
to ask as we wrap up the course. (I should
practice what I preach