Student: Ok, so now I want to find images that are both larger than a minimum size and a PNG. So I should write a new method.
Prof: Sure, how would this method work? What arguments would it take, and what would it return?
Student: Well, it should combine
largerThan and matchesExtension, so it needs the arguments of both methods, and it returns a boolean. But I’m clever! I’ll just call largerThan and matchesExtension from inside my new method and join them with &&. That way it’s only one line.Student: There we go,
bigPng is true and bigJpg is false. Clever, right?Prof: Nice work. Now, what if you want images that are a PNG or a JPG?
Student: Hmm, I’d need another method,
largerThanAndMatchesPngOrJpg. And then if I wanted images that are larger than a minimum size or a WEBP…Prof: Keep going. Every new way of combining queries needs a new method. And what happens as we add more fields to
ImageData?Student: Oh no. Every possible combination of queries needs its own method. I would never finish. I mean, also, there’s no way this is how someone at Google would do this, right? So what am I supposed to do instead?
Prof: What if a query was something you could pass around, like a value?
Practice
Fill in the blanks so that largerThanAndMatchesExtension is true only when the image is big enough and has the right extension, by calling the two queries that already exist.
record ImageData(String keywords, String fileType, int width, int height) {
boolean matchesExtension(String ext) {
return this.fileType.equals(ext);
}
boolean largerThan(int minWidth, int minHeight) {
return this.width >= minWidth && this.height >= minHeight;
}
boolean largerThanAndMatchesExtension(int minWidth, int minHeight, String ext) {
return && ;
}
}
void main() {
System.out.println("All tests succeeded!");
}
boolean matchesExtension(String ext) {
return this.fileType.equals(ext);
}
boolean largerThan(int minWidth, int minHeight) {
return this.width >= minWidth && this.height >= minHeight;
}
boolean largerThanAndMatchesExtension(int minWidth, int minHeight, String ext) {
return && ;
}
}
void main() {
System.out.println("All tests succeeded!");
}