CompSci 307 Fall 2022 |
Software Design and Implementation |
This exercise is intended to help you to practice using the "advanced" Java feature reflection: an amazing feature of many modern programming languages that lets you dynamically create objects and call methods based on String
values instead of having to know their exact names when the code is compiled. This flexibility lets you more easily hold their values in data structures or data files instead of hardcoding them directly within your code.
In pairs, switch which person actually writes the code after each numbered step (in industry this switch happens only 1-3 times per day). The person who is not actively coding can be advising, suggesting better names, looking up documentation, or searching the Internet for solutions to small problems you are likely to face, but not multi-tasking (i.e., doing their own work or socializing).
Also after each numbered step, you should be able to run your tests to verify your refactoring did not break any functionality, just improved the design!
For these refactorings, the only Java code changes need to be made in the browser.view.NanoBrowserView
class (other changes will involve making .properties
files):
makeButton()
method so that it that takes a String
parameter instead of an EventHandler
(so two different String
parameters)
makeButton()
, replace each Lambda that calls a single method with no parameters to just the name of that method (so it is still essentially hardcoded, but now using String
s instead of Lambdas).setOnAction()
within the makeButton()
method to use a new Lambda expression (instead of the one previously passed in) that uses the given string parameter to get a Method
object and then call its invoke()
method (and catches its many exceptions).makeButton()
method so that it that only takes one String
parameter (i.e., no extra parameter telling it what action to perform)
ResourceBundle
instance variable and, in the NanoBrowserView
class constructor, read the new properties file so that the method name to call is not hardcoded anywhere.ResourceBundle
) and the action for the button to perform (from the new ResourceBundle
). Again, this reduces the assumptions and what is hardcoded in your program.List<String>
instance variable that holds hardcoded values for the buttons' key names used in the properties files (i.e., it will hold the key strings "BackCommand"
, "NextCommand"
, and "GoCommand"
). makeInputPanel()
in the constructor to take the list of keys.Note, it is typically likely better overall design to make an abstraction (substitutable subclasses) rather than methods, because that is more flexible and recognizable than this simple example. But in either case, reflection can be used to make it data driven rather than hardcoded.