|
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
Last time, we we can have one method can call another method we wrote.
Re-capping, and continuing:We draw a picture of what's going on: main calls the TresAmigos_v3 constructor, which calls minStringOf3, which calls minString. Each has their own local variables. The stack of pending calls is called the run-time stack.
By the way, you've probably seen the run-time stack before, when your program encounters a run-time error: a “stack trace” gets printed out. We'll add a divide-by-zero error in maxString, and look at the output.
We can also see this stack using BlueJ's debugger: We'll click on the line number, and then repeatedly press the “Step into” button.
The full story: When we have maxStringOf3 call another method maxString, you might be wondering “Why doesn't that Java method call start with ‘object-dot’, like they pounded into our heads in 120?”
The answer is: it really does! If you call a method but you omit the ‘object-dot’, Java fills it in for you, with “this.”. That is, it calls the method in the same class.
By the way, this has a consequence: if we are in a context where there is no current object — no “this” — then Java can't fill in the “this.” for us, and we'll get an error. The codepad is one place where there is no “this”; the static method main is another. We'll talk about how to handle those situations later, when we properly discuss static methods (and static fields).
Here's an example of helper-methods in action: The tester code for TresAmigos provided actually grew through multiple stages:
One minor complication, is that to have nice output, reportError needs to be given not just the actual and expected results, but also the name of which test we are running (so that when an error message gets printed, we'll be able to figure out where the error is).
Version 4 assumed that the first name alphabetically is always Arturo, the second name is always Margerita, and the third name is always Zorro. Therefore it couldn't be used for testing other names — in particular, where two amigos might happen to have the same name (certainly something we should be testing!).
Here is a version where we give testGetters not just the object to be tested, but we also pass in the three expected answers (alphabetically). TresAmigosTester_v5.java
We call the process of taking repeated code and pulling it out into its own methods as refactoring1 Just like a good English essay goes through multiple drafts, good code also gets repeatedly refined.
1 Kinda like factoring in algebra, where you pull out repeated variables from the middle of a multiplication. ↩
home—info—lects—labs—exams—hws
textbook—tutor/PIs—java.lang docs—java.util docs
©2009, Ian Barland, Radford University Last modified 2009.Mar.23 (Mon) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |