レベルエンター山本大のブログ

面白いプログラミング教育を若い人たちに

BLOCKVROCKリファレンス目次はこちら

Guice User's Guide ■1. Introduction 

導入

The enterprise Java community exerts a lot of effort toward wiring objects together. How does your web application get access to a middle tier service, or your service to the logged in user or transaction manager? You'll find many general and specific solutions to this problem. Some rely on patterns. Others use frameworks. All result in varying degrees of testability and some amount of boilerplate code. You'll soon see that Guice enables the best of all worlds: easy unit testing, maximal flexibility and maintainability, and minimal repetition.

エンタープライズJavaのコミュニティーは、オブジェクト同士を結びつけるために、沢山の知恵を絞っています。たとえば「どうやってWebアプリケーションで中間層のサービスへのアクセスを取得するか」や「サービスをどのようにトランザクションマネージャーに登録するか」といった問題には、汎用的な方法にせよ、特殊な方法にせよ、たぶん沢山の解決方法があるでしょう。パターンに頼る人も要るでしょうし、フレームワークを使う人も要るでしょう。すべての結果は、テスト容易性と配線コードの量によって分類されます。これから紹介するGuiceは、ユニットテストの簡単さ、最大級の柔軟性とメンテナンス性、そして繰り返しの少なさにおいて、全世界で最高の方法かもしれません。

We'll use an unrealistically simple example to illustrate the benefits of Guice over some classic approaches which you're probably already familiar with. The following example is so simple in fact that, even though it will show immediate benefits, we won't actually do Guice justice. We hope you'll see that as your application grows, Guice's benefits accelerate.

これからGuiceのメリットを紹介して行きます。その際、現実にはありえないほどシンプルなサンプルをつかって、よく知られたいくつかのクラシックなやりかたと比較しながら紹介していきます。次の例はとてもシンプルなものです。実は即時にメリットを表しているのですが、Guiceを使うほどでもないものです。アプリケーションが大きくなるにつれてGuiceのメリットは加速して行くでしょう。

In this example, a client depends on a service interface. This could be any arbitrary service. We'll just call it Service.

このサンプルは、サービスインターフェイスに依存したクライアントです。これは任意のサービスと考えてください。以下では、ただサービスと呼ぶ事にします。

public interface Service {
  void go();
}

We have a default implementation of this service which the client should not depend directly on. If we decide to use a different service implementation in the future, we don't want to go around and change all of our clients.

このサービスにはデフォルトの実装がありますが、利用側はこのサービスに直接依存するべきではありません。もし、将来他のサービスの実装を使う事になったら、利用側のすべてを書き換えないといけなくなります。

public class ServiceImpl implements Service {
  public void go() { 
    ... 
  } 
} 

We also have a mock service which we can use in unit tests.
また、ユニットテストで使うためのモックサービスもあります。

public class MockService implements Service { 

  private boolean gone = false;

  public void go() {
    gone = true;
  }

  public boolean isGone() {
    return gone;
  }
}