例えば、年度 public class 年度{ private final String value; public 年度(String value){ if (value.length != 4){ throw new RuntimeException(“4桁以外”); } this.value = value; } // 2021 -> 21 public String toShortYear() { return this.value.substring(2); }
例えば、ISBN 欠落しがちな仕様を 型で表現することが できます (ISBNは10桁か13桁) public class Isbn { private final String isbn; public Isbn(String code) { // 10桁か13桁かチェック String len = code.length(); if (!(len == 10 || len == 13)) { throw new RuntimeException("エラー"); } String isbn1 = convert10to13(code); if (!”978”.equals(isbn1.substring(0, 3))) { throw new RuntimeException( “2段目バーコードを読み込んだ疑いあり” ); } this.isbn = isbn1; } }
例えば、ISBN 欠落しがちな仕様を 型で表現することが できます (ISBNは978はじまり) public class Isbn { private final String isbn; public Isbn(String code) { String len = code.length(); if (!(len == 10 || len == 13)) { throw new RuntimeException("エラー"); } String isbn1 = convert10to13(code); // 本当にISBNか。 if (!”978”.equals(isbn1.substring(0, 3))) { throw new RuntimeException( “2段目バーコードを読み込んだ疑いあり” ); } this.isbn = isbn1; } }
例えば、 山札・手札・場札 public class UnoGame{ 手札 手札; 山札 山札; 場札 場札; } public class 札 { String value; } public class 手札{ List<札> value; } public class 山札{ List<札> value; } public class 場札{ List<札> value; } 型がついたことにより、表現の 幅が広がりました。 また、操作するドメインが変わ り、メソッドがより適切な位置に 配備される可能性があります。