这是一个软件设计/最佳实践问题。 方便获取对象属性的字符串值的最优雅方法是什么?
考虑这个例子:
我有一个模型,数值保存为整数。
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);
}
问题是 - 有没有更好的方法来做到这一点,而无需创建多种格式化方法?也许是一种静态格式化方法?你如何进行这种数值格式化?
答案 0 :(得分:0)
所以你在这里有一个人物,他们负责很多事情:
1)格式化日期
2)在标志和字符串之间转换性别
3)转换测量值
将对象限制为一组相关职责是最佳做法。我会尝试为每一个创建一个新对象。
事实上,如果我对Single Responsibility Principle严格要求,我甚至会建议使用Measurement类来转换各种值(在此存储转换常量),以及另一个负责格式化的MeasurementPrinter类它以漂亮的方式(例如6英尺,2英寸或6英尺2英寸等)。
只是为了给你一个具体的例子我的意思
public class Person {
private Height height;
}
public class Height {
private static final double FT_TO_METERS = // just some example conversion constants
private int inches;
public double toFeet() {
return inches / IN_PER_FEET;
}
public double toMeters() {
return toFeet() * FT_TO_METERS;
}
所以现在人们对转换测量一无所知。
就像我说的那样,我甚至可以制作一个打印机对象:
public class HeightPrinter {
public void printLongFormat(Height height)
{
print(height.getFeet() + " feet, " + height.getInches() + " inches");
}
public void printShortFormat(Height height)
{
print(height.getFeet() + "', " + height.getInches() + "\"");
}
}
答案 1 :(得分:0)
我不认为你可以使用单一的格式化方法,因为不同的属性有不同的要求。但是,一些指导方针可以让您的生活更轻松:
将视图代码与模型代码分开:有一个单独的PersonView
类,它返回适合您的HTML输出的信息:
public class PersonView {
private Person person;
public String getTimeOfBirth() {
return formatDate(person.getTimeOfBirth());
}
...
}
使用强类型属性而不是基元: