More About Methods


Building And Testing The PeopleManager Class

Now that the Person class is finished it’s time to shift focus to the PeopleManager class. Referring to table 9-1 again reveals that the PeopleManager class will manage an array of Person objects and be able to insert Person objects into the array, delete Person objects from the array, and list the names and perhaps other information for Person objects contained in the array at any particular instant.

The same approach used to develop the Person class will be used here to develop the PeopleManager class. The development cycle will be applied iteratively to yield the final result.

Defining The PeopleManager Class Shell

Example 9.12 gives the source code for the PeopleManager class definition shell. Compile the code to ensure the class name matches the source file name and to catch any early structural mistakes.

Example 9.12: PeopleManager.java (1st Iteration)

image from book
 1     public class PeopleManager { 2 3 4 5     } // end PeopleManager class
image from book

To this shell you will add fields and methods.

Defining PeopleManager Fields

Table 9-1 says the PeopleManager class will manage an array of Person objects. This means it will need a field that is a single-dimensional array of type Person. Do not actually create the array. Instead, initialize the array reference to null like the fields of the Person class. Example 9.13 gives the modified source code for the PeopleManager class after the declaration of the people array.

Example 9.13: PeopleManager.java (2nd Iteration)

image from book
 1     public class PeopleManager { 2       Person[] people_array = null; 3 4 5     } // end PeopleManager class
image from book

Additional fields may be required but for now this is a good start. Time to add some methods.

Defining PeopleManager Constructor Methods

You can start with the constructor method. In fact I’ll show you how to overload the constructor method to create a default constructor. (Remember, a default constructor is one that has no parameters.) The PeopleManager constructor will need to create the people_array object. To do this it will need to know how long the array must be. You will supply the length via a constructor parameter. If you do not supply a length argument when you create an instance of PeopleManager then the default constructor will create the people_array with some default length value. In this example I will use a default length of 10. Example 9.14 gives the modified PeopleManager class after the constructors have been added.

Example 9.14: PeopleManager.java (3rd Iteration)

image from book
 1     public class PeopleManager { 2       Person[] people_array = null; 3 4       public PeopleManager(int size){ 5           people_array = new Person[size]; 6        } 7 8       public PeopleManager(){ 9          this(10); 10       } 11     }// end PeopleManager class
image from book

The constructor on line 4 takes an integer parameter named size and uses it to dynamically create the people_array in memory. The default constructor starts on line 8. It takes no parameters. On line 9 it calls the constructor defined on line 4 via the peculiar-looking this(10) call. The compiler will sort out which constructor this() refers to by examining the parameter list. Since there is a constructor defined to take an integer as a parameter it will use that constructor.

Compile the code to ensure you didn’t break anything and then add another method so you can start seriously testing the PeopleManager class.

Defining Additional PeopleManager Methods

I recommend adding the capability to add Person objects to the people_array first. Then you can add the capability to list their information, and finally, the capability to delete them.

A good candidate name for a method that adds a person would be addPerson(). Likewise, a good candidate name for a method that lists the Person objects in the array might be listPeople(). Example 9.15 gives the source code for the PeopleManager class containing the newly created addPerson() and listPeople() methods.

Example 9.15: PeopleManager.java (4th Iteration)

image from book
 1     public class PeopleManager { 2       Person[] people_array = null; 3       int index = 0; 4 5       public PeopleManager(int size){ 6           people_array = new Person[size]; 7        } 8 9       public PeopleManager(){ 10          this(10); 11        } 12 13       public void addPerson(String f_name, String m_name, String l_name, 14                              int dob_year, int dob_month, int dob_day, String gender){ 15          if(people_array[index] == null){ 16            people_array[index++] = new Person(f_name, m_name, l_name, 17                               dob_year, dob_month, dob_day, gender); 18          } 19          if(index >= people_array.length){ 20            index = 0; 21          } 22        } 23 24       public void listPeople(){ 25         for(int i = 0; i < people_array.length; i++){ 26           if(people_array[i] != null){ 27              System.out.println(people_array[i].getNameAndAge()); 28            } 29         } 30       } 31      }// end PeopleManager class
image from book

Let’s look at the addPerson() method for a moment. It has a parameter list that contains all the elements required to create a Person object. These include f_name, m_name, l_name, dob_year, dob_month, dob_day, and gender. The first thing the addPerson() method does is to check to see if a particular array element is equal to null. (The first time the addPerson() method is called on a particular PeopleManager object all the people_array elements will be null.) The variable index has been added as an instance field so that its value is maintained.

On line 19 the value of index is checked to see if it is greater than or equal to the length of the array. If it is its value is set to 0.

In this simple example the addPerson() method will add Person objects to the array until the array is full. From then on it will only insert Person objects if the array element it’s trying to access is null. (There are better ways to implement this method and they are left as exercises at the end of the chapter.)

The listPerson() method simply iterates over the people_array and, if the array element is not null, meaning it points to a Person object, it will call the getNameAndAge() method on the Person object and print the resulting String to the console.

Testing The PeopleManager Class

You can use the PeopleManagerApplication class once again to test the functionality of the PeopleManager class. Example 9.16 gives the source code for the modified PeopleManagerApplication class. Figure 9-10 shows the results of running this program.

Example 9.16: PeopleManagerApplication.java (Testing the PeopleManager class)

image from book
 1     public class PeopleManagerApplication { 2       public static void main(String[] args){ 3         PeopleManager pm = new PeopleManager();  // defaut constructor test 4 5       pm.addPerson("Steven", "Jay","Jones", 1946, 8, 30, Person.MALE); 6       pm.addPerson("Jeanie", "Sue", "Freeman", 1963, 10, 10, Person.FEMALE); 7       pm.addPerson("Richard", "Warren", "Miller", 1723, 2, 29, Person.MALE); 8 9       pm.listPeople(); 10 11       } // end main 12     }// end PeopleManagerApplication class
image from book

image from book
Figure 9-10: Results of Running Example 9.16

Referring to example 9.16 — the PeopleManager default constructor is tested on line 3. This also tests the other PeopleManager constructor. (Killed two birds with one stone here!) The addPerson() method is tested on lines 5 through 7 and the listPeople() method is tested on line 9. Everything appears to work as expected. You can now add the capability to delete Person objects and perhaps some other functionality.

Adding Features To The PeopleManager Class

The PeopleManager class now implements two out of three required features. You can add people to the people_array and you can list information about each person contained in the people_array. It’s now time to implement the capability to delete Person objects from the array. A good candidate name for a method to delete a Person object from the array is deletePerson(). (See — method naming isn’t so hard!) But wait — not so fast with the kudos. You just can’t delete a Person from an arbitrary element. It might be better instead to delete a Person object from a specific people_array element, in which case you might want to better name the method deletePersonAtIndex().

While you’re at it you might want to add the capability to insert Person objects into any element within the array. A good candidate name for such a method might be insertPersonAtIndex(). Example 9.17 gives the source code for the modified PeopleManager class.

Example 9.17: PeopleManagerClass.java (5th Iteration)

image from book
 1     public class PeopleManager { 2       Person[] people_array = null; 3       int index = 0; 4 5       public PeopleManager(int size){ 6           people_array = new Person[size]; 7        } 8 9       public PeopleManager(){ 10         this(10); 11       } 12 13      public void addPerson(String f_name, String m_name, String l_name, 14                             int dob_year, int dob_month, int dob_day, String gender){ 15         if(people_array[index] == null){ 16           people_array[index++] = new Person(f_name, m_name, l_name, 17                              dob_year, dob_month, dob_day, gender); 18         } 19         if(index >= people_array.length){ 20           index = 0; 21         } 22      } 23 24     public void deletePersonAtIndex(int index){ 25         assert((index >= 0) && (index < people_array.length)); 26         people_array[index] = null; 27     } 28 29     public void insertPersonAtIndex(int index, String f_name, String m_name, String l_name, 30                            int dob_year, int dob_month, int dob_day, String gender){ 31        assert((index >= 0) && (index < people_array.length)); 32        people_array[index] = new Person(f_name, m_name, l_name, dob_year, dob_month, dob_day, gender); 33     } 34 35     public void listPeople(){ 36       for(int i = 0; i < people_array.length; i++){ 37         if(people_array[i] != null){ 38            System.out.println(people_array[i].getNameAndAge()); 39          } 40       } 41    } 42  }// end PeopleManager class
image from book

Examine closely for a moment the deletePersonAtIndex() method. It declares one parameter named index. This parameter name will hide the field named index which is the desired behavior in this case. There is also a danger that the argument used in the deletePersonAtIndex() method call might be invalid given the length of the people_array. The assert mechanism is used on line 25 to enforce the precondition that the value of the index parameter must be greater than or equal to zero or less than the length of the people_array. The assert mechanism is also used in the insertPersonAtIndex() method on line 31.

The assert mechanism is normally off or unrecognized when you compile your code using the javac compiler. To enable the assert mechanism you will have to compile the PeopleManager class using the following javac command-line arguments:

 javac -source 1.4 PeopleManager.java

To test the PeopleManager class with its new assertion capabilities you will have to enable assertions in the Java virtual machine by using the -ea command-line argument when you run the PeopleManagerApplication program. Here’s how the java command would look:

 java -ea PeopleManagerApplication

Example 9.18 gives the source code for the PeopleManagerApplication class that tests the newly added PeopleManager class functionality. Figure 9-11 shows the results of running this program.

Example 9.18: PeopleManagerApplication.java (Testing new PeopleManager class functionality)

image from book
 1     public class PeopleManagerApplication { 2       public static void main(String[] args){ 3        PeopleManager pm = new PeopleManager();  // defaut constructor test 4 5        pm.addPerson("Steven", "Jay","Jones", 1946, 8, 30, Person.MALE); 6        pm.addPerson("Jeanie", "Sue", "Freeman", 1963, 10, 10, Person.FEMALE); 7        pm.addPerson("Richard", "Warren", "Miller", 1723, 2, 29, Person.MALE); 8 9        pm.listPeople(); 10 11       pm.deletePersonAtIndex(1); 12       pm.insertPersonAtIndex(1, "Coralie", "Sylvia", "Miller", 1965, 8, 3, Person.FEMALE); 13 14       System.out.println(); 15       pm.listPeople(); 16 17       pm.deletePersonAtIndex(-3);  // test assertion - code should fail here! 18       } // end main 19    }// end PeopleManagerApplication class
image from book

image from book
Figure 9-11: Results of Running Example 9.18

The assertion mechanism made the code fail as expected. Assertions are best used during code development to help with testing and debugging. Assertions are then usually disabled after the code has been thoroughly tested.

Quick Review

The PeopleManager class implementation process followed the same pattern as that of class Person. Start with the class shell and add fields and methods as required to implement the necessary functionality. Develop incrementally by applying the development cycle in an iterative fashion.

The Java assertion mechanism can be used to thoroughly test and debug code. Assertions are usually disabled upon completion of the testing phase.




Java For Artists(c) The Art, Philosophy, and Science of Object-Oriented Programming
Java For Artists: The Art, Philosophy, And Science Of Object-Oriented Programming
ISBN: 1932504052
EAN: 2147483647
Year: 2007
Pages: 452

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net