ビルダーパターンが便利

ビルダーパターンが便利だったので、まとめちゃいます。

今、自分が担当しているプロジェクトのテストコードで、主要なクラス(ドメイン駆動設計で言うとエンティティクラス)をnewしているコードが複数のテストコードに散らかっていた。 で、主要なクラスにフィールド値を追加・削除すると、各地に散らかっているテストコードを直すハメになってしまう。

そこで、主要なクラスのビルダーをテストコード側で作成して、主要なクラスをnewしているコードをすべてビルダーに置き換えたら、すげーすっきりした。

ビルダーパターンの例はこんな感じ。

public class Member {

    private final String fullName;
    private final String birthDate;
    private final String sex;
    private final String address;
    private final String tel;

    public Member(Builder builder){
        this.fullName = builder.fullName;
        this.birthDate = builder.birthDate;
        this.sex = builder.sex;
        this.address = builder.address;
        this.tel = builder.tel;
    }


    public static class Builder{
        private String fullName = "日本太郎";
        private String birthDate = "1983/1/1";
        private String sex = "man";
        private String address = "東京都";
        private String tel = "090-1234-5678";

        public Builder fullName(String fullName){
            this.fullName = fullName;
            return this;
        }

        public Builder birthDate(String birthDate){
            this.birthDate = birthDate;
            return this;
        }

        public Builder sex(String sex){
            this.sex = sex;
            return this;
        }

        public Builder address(String address){
            this.address = address;
            return this;
        }

        public Builder tel(String tel){
            this.tel = tel;
            return this;
        }

        public Member build(){
            return new Member(this);
        }

    }
}

利用側のコードはデフォルト値から変更したいフィールドだけを更新かけてあげて、最後にbuildメソッドを呼び出すだけ。

Member member = new Member.Builder().address("大阪府").build();

今の所、プロダクトコードでビルダーパターンを使った方が良い機会が見つかっていない。 また、見つかったら、ブログにアップしよう。