More Composition
Student: These images are kind of cool. What’s next?
Prof: Can you think of a way to use the image constructors we’ve learned so far to draw a picture?
Student: Not sure, ideas?
Prof: There are a lot of countries’ flags that are made out of simple shapes combined!
Student: Oh right! Like the US flag?
Prof: Let’s try the 50 stars after we’ve learned a little more! How about, say, the French flag?
Student: Oh, OK. So that’s just three rectangles next to each other. Blue, white, red. I need to pick some sizes, they all have the same width and height…
Student: Huh, an error?
Prof: That’s great!
Student: Seeing an error is great?
Prof: Errors are a signal that we’re about to learn something! We should embrace the feedback. Look back at the
Beside constructor. How many arguments does it take and what are their names?Student: It says “Pict left” and “Pict right”. So I guess two, called left and right?
Prof: And how many arguments are given to
Beside in your code?Student: Three: blue, white, red.
Prof: That’s what the error is saying: there’s no constructor called
Beside that takes in three Picts.Student: Oh, so I guess we can’t do the flag?
Prof: We can use more composition! What if you made one image that was the white and blue stripe together, then another image that put that one next to the red stripe?
Student: Oh… something like this?
Prof: That’s cool! Nice work.
Student: That’s super interesting. Could I keep building on this?
Prof: Sure – you can compose as much as you like. You could have a German flag (more stripes) on top of a French flag, beside the Bangladesh flag we saw before, above a tree, and so on. A few vocabulary terms:
- composition is the idea of putting values together into a new fused or combined behavior or value.
- We can also call these image objects nested, in the sense that one image is a field of a different image object.
Student: I see, so composition lets us build up nested structures. Some nested structures can be quite large!
Prof: You’ve got it.
Practice
Composition is not only for images. Here are three records. A
LectureSession has a Time and a Room as fields, so building one means building those first. Use composition to define cse11 as the lecture session for CSE 11: 9:30 in the morning, in Galbraith 242.record Time(int hour, int minute) {}
record Room(String building, String room) {}
record LectureSession(Time startTime, Room room) {}
record Room(String building, String room) {}
record LectureSession(Time startTime, Room room) {}
Now the other way around. This code builds a
Point origin = new Point(0.0, 0.0);
Point corner = new Point(3.5, 4.25);
LineSegment diagonal = new LineSegment(origin, corner);
LineSegment out of two Points, and each Point is made from two doubles. Write the two record definitions that make it compile.Point origin = new Point(0.0, 0.0);
Point corner = new Point(3.5, 4.25);
LineSegment diagonal = new LineSegment(origin, corner);