Break It Down

Sometimes package access is not enough or is not available. Finding yourself unable to test tightly encapsulated functionality may indicate that your class is doing too much. Often you create private methods to simplify the implementation of the public interface. However, methods generally should be small. Your ability to functionally decompose a method into smaller methods of higher abstraction could mean that those methods constitute another class when taken together, particularly if they are reused.

Extracting your private implementation into a class can make it directly testable. Java allows more than one class in a file as long as the additional classes are not public; those classes have package scope. You can also make the extracted classes public for easier testing.

Once you have extracted the new class, you need to decide how to use it. You can make it part of the inheritance hierarchy or you can compose it within the original class and invoke it through that reference. Listing 9-5 shows an example of a class that can be broken up in both of these ways, and Listing 9-6 shows it broken up into three classes.

Listing 9-5: A Java class awaiting refactoring

public class Car {
  public void start() {
    ...
    igniteEngine();
    ...
  }

  private void igniteEngine() { ... }
}

Listing 9-6: Refactoring Listing 9-5 such that the separation of concerns enhances testability

public class Engine {
  public void ignite() { ... }
}

public class MotorVehicle {
  private Engine engine;

  protected void igniteEngine() {
    engine.ignite();
  }
}

public class Car extends MotorVehicle {
  public void start() {
    ...
    igniteEngine();
    ...
  }
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.38.176