BruceEckel / OnJava8-Examples

Code Examples for the book "On Java 8"

Home Page:http://www.OnJava8.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is the parameter redundant

nengquqiaoxiaoyun opened this issue · comments

In Thinking In Java, Chapter 14.3
Here is the class PetCount:

// typeinfo/PetCount.java
...

public class PetCout {
...

   public static void countPets(PetCreator creator) {
       PetCounter counter = new PetCounter();
           for(Pet pet : creator.createArray(20)) {
              ...  
          }
   }
}

Here is used creator to create Pet[].

In On Java 8
Here is the class PetCount:

// typeinfo/PetCount.java
...

public class PetCout {
...

   public static void countPets(PetCreator creator) {
       PetCounter counter = new PetCounter();
           for(Pet pet : Pets.array(20)) {
              ...  
          }
   }
}

Here is used Pet's method array to create Pet[], and there is a Creator in class Pets, the instance is LiteralPetCreator

// typeinfo/pets/Pets.java
// Facade to produce a default PetCreator

public class Pets {
    public static final PetCreator CREATOR = new LiteralPetCreator();

    public static Pet[] array(int size) {
        Pet[] result = new Pet[size];
        for (int i = 0; i < size; i++)
            result[i] = CREATOR.get();
        return result;
    }

}

original text:

Because PetCount.countPets() takes a PetCreator argument, we can easily test the LiteralPetCreator (via the above Façade):
// typeinfo/PetCount2.java import typeinfo.pets.*;
public class PetCount2 {
public static void main(String[] args) {
PetCount.countPets(Pets.CREATOR);
}
}

We create Pet[] by Pet's method, and we do not need test the LiteralPetCreator like this
PetCount.countPets(Pets.CREATOR);
The LiteralPetCreator is in class Pets

PetCount.countPets(null);
This also works