Java Reference
In-Depth Information
Tutorial: Tidying Up Our Messy Method
In addition to using the new and improved Employee class, we want to organize EnterEmpInfo better and use a few
global (class) variables instead of many local (method) variables. In addition, when actionPerformed is executed,
the frame information should be retrieved and placed in an Employee object. However, currently actionPerformed
creates an Employee object. This means a new Employee object is created each time the user clicks a button. This
is not very efficient. Instead, a single global Employee variable (and object) should be created and its properties
changed each time actionPerformed is invoked (i.e., each time the user clicks a button). So, the Employee variable
(emp) will be changed to a class (global) variable and assigned an Employee object only once.
The source code to retrieve the text field values and assign them to the Employee properties will be placed in
a private method called setEmployeeProperties. (Creating a new private method allows other methods in the class
to invoke this function.) The setEmployeeProperties method will be invoked from the actionPerformed method. In
EnterEmpInfo:
1.
Add the following new class variable definition:
private Employee emp = new Employee();
2.
Before the main method, add the following method that retrieves the various text field
values and assigns them to the appropriate Employee property:
private void setEmployeeProperties() {
emp.setEmpName(empNameTF.getText());
emp.setEmpStreet(empStreetTF.getText());
emp.setEmpCity(cityTF.getText());
emp.setEmpState(stateTF.getText());
emp.setEmpZip(zipTF.getText());
emp.setPayRate(Double.parseDouble(empPRTF.getText()));
emp.setExemptions(Integer.parseInt(exmpChoice.getSelectedItem()));
}
The first five statements are relatively easy. We simply used each text field's getText statement as a parameter in
the appropriate property setter method. Notice that we eliminated the need for a method variable by using the result
of the getText method as the setter parameter. This efficiency becomes even more apparent in the last two statements.
In addition to retrieving the text, these statements also parse the text into a primitive. Earlier three statements and two
method variables were used as follows:
String stringPayRate = EmpPRTF.getText();
double doubleRate = Double.parseDouble(stringPayRate);
emp.setPayRate(doubleRate);
3.
In actionPerformed, add the following as the first statement so that the
setEmployeeProperties method is invoked:
this .setEmployeeProperties();
Notice that many of the remaining statements set up method variables. We have eliminated the need for many of
these by using an Employee object and the setEmployeeProperties methods.
4.
Delete the statements that define the method variables stringTaxAmt, empPayRate,
double-EmpPR and doubleGross.
This will cause several syntax errors to be flagged in the source code.
 
Search WWH ::




Custom Search