Red > Green > Refactor > Red

cycle is based on desire

Builder Pattern (Java)

Effective Java より

数多くのコンストラクタパラメータに直面した時の対処法

src
 |
 +-- jp.ymatsukawa
          |
          +-- builder
          |      |
          |      +---- SignupUser.java
          |
          +-- Main.java

jp.ymatsukawa/Main.java

package jp.ymatsukawa;

import jp.ymatsukawa.builder.SignupUser;

public class Main {
  public static void main(String[] args) {
    try {
      SignupUser testUser =
        new SignupUser
          .Builder("test@example.com", "testpass")
          .name("test")
          .build();
    } catch(Exception e) {
      e.printStackTrace();
    }

    try { // NullPointerException Will happen
      SignupUser ymatsukawa =
        new SignupUser
          .Builder(null, null)
          .name("ymatsukawa")
          .gender("male")
          .skill("(゚∀゚)")
          .remark("hello world")
          .build();
    } catch(Exception e) {
      e.printStackTrace();
    }
  }
}

jp.ymatsukawa/builder/SignupUser.java

package jp.ymatsukawa.builder;

public class SignupUser {
  private final String email;    // required item
  private final String password; // *
  private final String name;     // option item
  private final String gender;   // *
  private final String skill;    // *
  private final String remark;   // *

  public static class Builder {
    //===== required =====//
    private String email;
    private String password;

    //----- option -----//
    private String name   = "";
    private String gender = "";
    private String skill  = "";
    private String remark = "";

    public Builder(String email, String password) {
      this.email    = email;
      this.password = password;
    }

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

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

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

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

    public SignupUser build() throws NullPointerException {
      // validate required item
      // below is example
      if((this.email == null) || (this.password == null)) {
        throw new NullPointerException("null is pointed at required item");
      }
      return new SignupUser(this);
    }
  }

  private SignupUser(Builder builder) {
    this.email    = builder.email;
    this.password = builder.password;
    this.name     = builder.name;
    this.gender   = builder.gender;
    this.skill    = builder.skill;
    this.remark   = builder.remark;
  }
}

Qiita 記事を書留め

qiita.com