Student: OK I think I’m starting to get it a little bit now. Here’s a question – do all
records have methods?Prof: Great question. Not all of them have them, but all of them can have them, and they’re often useful. Our images have them, for example. Some of them are called convenience methods because they do something you could do anyway, they’re just easier to type and read.
Student: Interesting, what does that look like?
Prof: So far we’ve put two images beside each other with
new Beside(pict1,
pict2), right?Student: Sure, I remember that.
Prof: Well there’s also a method called beside. Here’s its signature:
Pict beside(Pict other)You can think of it as being defined in every one of the records like Circle and Rect and so on. Here are two examples of using beside, one with the constructor and one with the method:
Student: Interesting! I like how the method version reads. But wait, there’s something really weird there. I thought the thing before the
. in a method call had to be the name of a definition, like blue.Prof: That’s a great observation. The whole expression
blue.beside(white) evaluates to one Pict (a Beside object), and then that object is used to call .beside(red) – it is the receiver for that method call. It never got named by the program, but it does exist briefly. Just like how the first argument to new Beside(____, red) is a use of the Beside constructor that makes a blue-and-white-stripe image.Student: Hmmm OK.
Prof: This specific style is called method chaining, where you use the result of a previous method call as the receiver of the next. You can always name the intermediate value if you want! It doesn’t have any special behavior. It’s just a nice way to write and read that line of code.
Student: I think I get it! So do those methods exist for all the constructors for images?
Prof: For all the ones that combine two images, yes! There’s
Pict above(Pict other), Pict overlay(Pict other), and so on.Practice
Each program below builds a picture in named steps, from three
Pict definitions dot, left, and right. Pick the method chain that builds the same picture in one line.Pict pair = left.beside(right);
Pict pic = dot.overlay(pair);chained:
Pict marked = dot.overlay(left);
Pict pic = marked.beside(right);chained: