これはソフトウェア設計/ベスト プラクティスに関する質問です。オブジェクト属性の文字列値を便利に取得する最もエレガントな方法は何ですか?
次の例を検討してください。
数値が整数として保存されたモデルがあります。
class Person {
integer time_of_birth; // unix timestamp
integer gender; // 1 - male, 2 - female
integer height; // number of millimeters
integer weight; // number of grams
string name;
}
意味のあるビュー (HTML ページなど) を作成するには、数値情報を人間が読める形式 (文字列) で出力する必要があります。これまでのところ、文字列以外の属性の文字列表現を返すメソッド「attributename_str()」を追加することでそれを行っています。
method time_of_birth_str() {
return format_date_in_a_sensible_manner(this.time_of_birth);
}
method gender_str() {
if this.gender == 1 return 'male';
if this.gender == 2 return 'female';
}
method height_str(unit, precision) {
if unit == meter u = this.height/some_ratio;
if unit == foot u = this.heigh/different_ratio;
return do_some_rounding_based_on(precision,u);
}
質問は - 多数のフォーマット方法を作成せずに、これを行うためのより良い方法はありますか? おそらく単一の静的フォーマット方法ですか?この数値の書式設定はどのように行うのですか?