Locked History Actions

guice/Manual/BestPractices/AvoidConditionalLogicInModules

モジュール内条件ロジックを避けよ

異なる条件の場合に異なる操作を行うことができるようにモジュールを構成したいという誘惑に駆られることがある。

public class FooModule {
  private final String fooServer;

  public FooModule() {
    this(null);
  }

  public FooModule(@Nullable String fooServer) {
    this.fooServer = fooServer;
  }

  @Override protected void configure() {
    if (fooServer != null) {
      bind(String.class).annotatedWith(named("fooServer")).toInstance(fooServer);
      bind(FooService.class).to(RemoteFooService.class);
    } else {
      bind(FooService.class).to(InMemoryFooService.class);
    }
  }
}

条件ロジックそれ自体は悪くない。 しかし、コンフィギュレーションがテストされないと問題が発生する。 この例では、開発時にはInMemoryFooServiceが使われ、製品ではRemoteFooServiceが使われる。 しかし、特定のケースについてのテストがないと統合されたアプリの中でRemoteFooServiceがきちんと動作するかを検証できない。

To overcome this, minimize the number of distinct configurations in your applications. If you split production and development into distinct modules, it is easier to be sure that the entire production codepath is tested. In this case, we split FooModule into RemoteFooModule and InMemoryFooModule. This also prevents production classes from having a compile-time dependency on test code.