カプセル化カプセル化を行った場合・行っていない場合の修正に対する柔軟さを検証。 Advertisementカプセル化していないクラス
Profileクラス
public class Profile{
public String name;
public String age;
}
Profileクラスを利用するクライアントのコード
public class Main{
public static void main(String[] args){
Profile profile = new Profile();
profile.name = "なまえ";
profile.age = "10";
System.out.println(Profile.name);
System.out.println(Profile.age);
}
}
ここでProfileクラスのageフィールドをint型に変更する。この場合、以下の修正を行わなければならない。
変更後Profileクラス
public class Profile{
public String name;
public int age;
}
変更後Mainクラス
public class Main{
public static void main(String[] args){
Profile profile = new Profile();
profile.name = "なまえ";
profile.age = 10;
System.out.println(Profile.name);
System.out.println(Profile.age);
}
}
クライアント側でProfileクラスの内部構造に依存しているコードを記述してしまっているため、変更の影響範囲が大きくなり、両方のクラスを修正する必要がある。 カプセル化を行ったクラス
ここで、Profileクラスをカプセル化したコードを以下に示す。
public class Profile{
private String name;
private String age;
public void setName(String name){
this.name = name;
}
public void setAge(String age){
this.age = age;
}
public String getName(){
return this.name;
}
public string getAge(){
return this.age;
}
}
上記のカプセル化を行ったクラスを利用するクライアントのコードは以下のようになる。
public class Main{
public static void main(String[] args){
Profile profile = new Profile();
profile.setName("なまえ");
profile.setAge("10");
System.out.println(profile.getName());
System.out.println(profile.getAge());
}
}
カプセル化を行ったクラスのageをint型に変更する場合、以下の変更が必要となる
public class Profile{
private String name;
private int age;
public void setName(String name){
this.name = name;
}
public String getName(){
return this.name;
}
public void setAge(String age){
this.age = Integer.parseInt(age);
}
public String getAge(){
return Integer.toString(this.age);
}
}
クライアント側の変更 なし。クライアントがProfileクラスの内部構造に依存するコードを書かなくなった(インタフェースのみに依存している)ため、Profileクラスを変更しても、クライアント側への影響がなくなった。 まとめ
クラスのカプセル化を行い、変更に強い設計をすることはオブジェクト指向の基本であり、比較的楽に実装できるにもかかわらず、多くの恩恵を受けることができる。
|