Test-Only Interfaces

You can mitigate the exposure of changing access levels. You can introduce test-only interfaces to combine access level change with a weaker form of breaking down your class. In general, it enhances extensibility and testability to use interfaces as the primary types rather than concrete classes. From an object-oriented design perspective, this separates your definition of the behavioral specification from its implementation. Also, Java’s mocking frameworks work best with interfaces, although they are getting better at handling concrete classes.

By using interfaces as the primary types, callers can only access the methods defined in that interface unless they have the bad manners to use the implementation class directly. This reduces the importance of the access levels of the noninterface members. However, you can further make the role of these methods explicit by grouping them into an alternate interface that the concrete class implements, as shown in Listing 9-7.

Listing 9-7: Using a test-only interface in Java to help designate access-elevated members. Production code would refer to the Toaster interface, but test code could use the ToasterTester interface.

public interface Toaster {
  public void makeToast();
}

public interface ToasterTester extends Toaster {
  public void verifyPower();
  public void heatElements();
  public void waitUntilDone();
  public void stopElements();
  public void popUpToast();
}
public class DefaultToasterImpl implements ToasterTester {
  public void makeToast() {
    verifyPower();
    heatElements();
    waitUntilDone();
    stopElements();
    popUpToast();
  }

  ...
}

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

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