2012-08-16 17 views
1

这是一个软件设计/最佳实践问题。 什么是最方便的方法获取对象属性的字符串值?获取对象属性的字符串表示的最佳方法

考虑这个例子:

我有保存为整数数值模型。

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

所以你在这里有一个人对象,他们是负责不少东西:
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() + "\""); 
    } 
    } 
0

我不认为你可以逃脱一个格式化的方法,因为不同的属性有不同的要求。但一对夫妇的指引可以让你的生活变得更轻松:

单独从模型代码视图代码:有一个单独的PersonView类返回合适的信息为你的HTML输出:

public class PersonView { 
    private Person person; 

    public String getTimeOfBirth() { 
    return formatDate(person.getTimeOfBirth()); 
    } 

    ... 
} 

使用强类型的属性,而不是原语:

  • 使用日期对象,而不是一个整数时间戳。
  • 为性别而不是整数创建一个枚举。
  • 使用单位创建高度和重量类,而不是使用单位的整数。
相关问题