LoginSignup
0
0

More than 3 years have passed since last update.

【Java】変更に強いコード追加編 - Validation 機能

Posted at

もっと!変更に強いコードを目指す

  • 前回の 【Java】変更に強いコード実践編 - 値オブジェクト2(Value Object) では、
    Valueオブジェクトを使ってタイポがない、凡ミスがないコードにしようo(^^)o
  • ということで、建物の緯度経度を表すBuildeingクラスを作りました
  • Valueオブジェクトで型を指定することで、Buildingに渡す引数の順番間違え(Latitude、Longitudeの順番)を防止できました👍

Validation機能追加

  • さらに堅牢なコードを目指し、LatitudeにLongitudeの値(139.761102f)を入れてしまうことを防ぎたい。。。
  • 値オブジェクトの初期化時に間違った実値を渡してしまう事を抑止するのはValidation機能で行うことができます
new Latitude(139.761102f),
new Longitude(35.663114f)
  • Latitudeクラスを以下のように変更したら、範囲外の値を入力した時に実行時例外を出すことができるので、さらに堅牢なコードになりますね⭐️o(^o^)o
  • 構成は以下のようになっています
Project Root
└─src
    └─ main
        └─ java  
            └─ Main
        └─ values
            └─ Building
            └─ Building2
            └─ BuildingName
            └─ Longitude
            └─ Latitude
            └─ Main
Latitude.java
package values;

public class Latitude {
    private float value;
    public Latitude(float value) throws Exception {
        if(value < -90 || 90 < value ){
            throw new Exception("Out of Range");
        }
        this.value = value;
    }

    public float getValue() {
        return value;
    }
}
Main.java
package values;

public class Main {

    public static void main(String[] args) throws Exception {

        Building mitaka = new Building(
                new BuildingName ("三鷹の森"),
                //fつけないとリテラルとして認識されない
                new Latitude(35.6962303f),
                new Longitude(139.5704895f)
        );

        /*緯度と経度の値を逆にしてしまった場合にValidationが効いて実行時エラー
           Exception in thread "main" java.lang.Exception: Out of Range
         */ 
        Building totoro = new Building(  
                new BuildingName ("トトロの森"),
                new Latitude(139.4219994f), 
                new Longitude(35.7818004f)
        );

        /*緯度と経度の引数順を間違えてしまった場合はコンパイルエラー
        Building totoro = new Building(
                new BuildingName ("トトロの森"),
                new Longitude(139.4219994f),
                new Latitude(35.7818004f)
        );
         */

        /*コンパイルエラーにならない例
        Building2 totoro2 = new Building2(
                "トトロの森",
                139.4219994f,
                35.7818004f
        );
         */

        System.out.println("pause");
    }
}

実行時エラーでミスを未然に防げますね〜
実行時.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0