☰ Contents Recipe for Success

A Helping Hand

Student: You were suggesting that my pizza example had more we could learn from it.
Prof: Indeed! Let’s have a look at your code again
Student: Here it is:
Prof: Here’s a version I think would read much better:
Student: I mean, sure, but your code clearly doesn’t run. How is that better?
Prof: Well, let’s say it ran and gave all the same answers as yours. Would you like it better?
Student: I mean, sure. It’s nice to not write all the multiplication and division over and over.
Prof: Great! OK, so make it run – define the area method.
Student: Hmmm… I guess it uses a lot of the same code we just deleted.
Prof: Indeed! Let’s think it through. Based on how we used it, what’s its name, its return type, and its parameters?
Student: Well the name is obviously area. And it must return a double because that’s what we were calculating before.
Prof: Great so far! What about the arguments?
Student: Does it take a Pizza?
Prof: Oh that’s a good instinct, but no. The receiver of area will always be a Pizza, and we don’t need any more information. Unlike betterDeal, area only works with the receiver, so it doesn’t take any arguments! And when betterDeal calls area() with nothing in front of it, the receiver is the same pizza betterDeal was called on.
Student: Hmm OK. So that’s like…
Prof: Ah, very nice. Isn’t that pleasant? What are some benefits of having done this?
Student: Well, I do think it’s nice to just use .area() in the betterDeal method. I can see more quickly what it does.
Prof: Can you think of any other benefits?
Student: Hmm… wait, can we use area for any Pizza now?
Prof: That’s right! This area method started as what we call a “helper” method, whose job is just to make another method simpler. But a lot of times a helper method can be useful on its own, too.

Practice

This method computes a distance from 0 twice:

boolean furtherFrom0Than(Point other) {
  double thisDistance = Math.sqrt(x * x + y * y);
  double otherDistance = Math.sqrt(other.x * other.x + other.y * other.y);
  return thisDistance > otherDistance;
}

Finish the version below that uses the dist0 helper instead.

record Point(double x, double y) {
double dist0() {
return Math.sqrt(x * x + y * y);
}
boolean furtherFrom0Than(Point other) {
return > ;
}
}
Point far = new Point(3, 4);
Point near = new Point(1, 1);
boolean farFurther = far.furtherFrom0Than(near);
boolean nearFurther = near.furtherFrom0Than(far);