私はほとんどの不変データ オブジェクトを次のスタイルで書いています。これは、「次世代」または「機能的」と表現されることもあります。
public class Point {
public final int x;
public final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
インターフェイスで指定されたデータ オブジェクトに同じスタイルを使用したいと思います。
public interface Point {
public final int x;
public final int y;
}
public class MyPoint {
public MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
}
public class Origin {
public Origin() {
this.x = 0;
this.y = 0;
}
}
しかし、これは Java では許可されていないため、実装だけでなくインターフェイス コードでもエラーが発生します。
コードを次のように変更できます
public interface Point {
public int x();
public int y();
}
public class MyPoint {
private int mx, my;
pulic MyPoint(int x, int y) {
mx = x;
my = y;
}
public int x() {return mx;}
public int y() {return my;}
}
public class Origin {
public int x() {return 0;}
public int y() {return 0;}
}
しかし、それはより多くのコードであり、API でほぼ同じ単純さを与えるとは思いません。
私のジレンマから抜け出す道が見えますか? それとも、個人的にはさらにシンプルな 3 番目のスタイルを使用していますか?
(変更可能/不変、getterSetter/新しいスタイル、またはプライベート/パブリック フィールドの議論にはあまり興味がありません。)