|
home—info—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
We will make one new class — Describable — which includes the code repated of Room and Treasure. Then Room and Treasure will extend Describable.
super( … ) . |
More troubling than the repeated fields and getters, were some static methods dealing for list of Rooms/Treasures: treasuresToString and roomsToString were repeated code, and we also had a method roomsToNamesString (or some-such used by Room's toString) which could apply equally well to Treasures.
You would certainly think that you just change the parameter-type from LinkedList<Room> to LinkedList<Describable>. Alas: it's not quite so simple, when you have collections of items. You need to give the parameter-type as to LinkedList<? extends Describable>. (Think of this as “a list of Describables, where everything in the list is the same type.”1.)
Once you have this method describablesToString, you can collapse TextIO's two methods selectRoom and selectTreasure into one. Run your program, to make sure everything works the same as before (with even less code).
Optional: Add the GuiIO class to your project, and have your program use it instead of GuiIO.
You can even make a abstract class IO. It declares methods display, prompt, etc. each of them as an abstract method (a declaration without a body):
public abstract String prompt( String msg ) |
Once you have the abstract class,
both TextIO and GuiIO will extend IO.
Then, instead of a local variable whose declared type is TextIO,
that variable's declared type should be IO.
This variable will be
initialized with (either) a new GuiIO() or a new TextIO().
(This time, the refactoring it doesn't eliminate any repeated code,
but it helps sets us up for any future methods which want to be given an IO
but don't care which type they get.)
Since there is no potential for ever having any code or constants inside abstract class IO, really it should instead be declared as an interface. Feel free to do so.
1Note that “LinkedList<Describable>” refers to a list which may contain both Rooms and Treasures at the same time. But that's not what we're passing in, which is why the extra “question-mark” notation is needed. ↩
home—info—exams—lectures—labs—hws
Recipe—Laws—lies—syntax—java.lang docs—java.util docs
©2007, Ian Barland, Radford University Last modified 2007.Aug.27 (Mon) |
Please mail any suggestions (incl. typos, broken links) to ibarlandradford.edu |