Java重构示例四

Java重构示例四
关键字:Java 程序设计 重构 示例 技巧 原则 优化 方法
序言
本文通过Java示例代码片段展示了常用重构原则和技巧,供初级开发人员参考。精致的代码能够清楚传达作者的意图,精致的代码是最好的注释,精致的代码非常容易维护和扩展。程序员阅读精致的代码如同大众欣赏优美的散文一样享受。
16    减少重复计算
16.1    重构前

if(list != null && list.size() > 0){
  for(int i = 0; i < list.size(); i++){
    //skip...
  }
}

16.2    重构后

if(list != null){
  for(int i = 0, len = list.size(); i < len; i++){
    //skip...
  }
}

17    何时需要何时创建
17.1    重构前

public static Date parseDate(String date) throws ParseException {
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

  if ((date == null) || (date.equals(""))) {
    return null;
  }
  else {
    try {
      return formatter.parse(date);
    } catch (ParseException pe) {
      throw new ParseException(pe.getMessage(), pe.getErrorOffset());
    }
  }
}

17.2    重构后

public static Date parseDate(String date) throws ParseException {
  if ((date == null) || (date.equals(""))) {
    return null;
  }
  else {
    try {
      SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
      return formatter.parse(date);
    } catch (ParseException pe) {
      throw new ParseException(pe.getMessage(), pe.getErrorOffset());
    }
  }
}

18    利用已有的计算结果
18.1    重构前

public static final String DAY = "DAY";
public static final String MONTH = "MONTH";
public static final String YEAR = "YEAR";
public static final String HOUR = "HOUR";
public static final String MINUTE = "MINUTE";
public static final String SECOND = "SECOND";
public static final String WEEK = "WEEK";

public long toMilliseconds(String unit) {
  if (unit == null) {
    return 0L;
  } else if (unit.equals(SECOND)) {
    return 1 * 1000L;
  } else if (unit.equals(MINUTE)) {
    return 60 * 1000L;
  } else if (unit.equals(HOUR)) {
    return 60 * 60 * 1000L;
  } else if (unit.equals(DAY)) {
    return 24 * 60 * 60 * 1000L;
  } else if (unit.equals(WEEK)) {
    return 7 * 24 * 60 * 60 * 1000L;
  } else if (unit.equals(MONTH)) {
    return 30 * 24 * 60 * 60 * 1000L;
  } else if (unit.equals(YEAR)) {
    return 365 * 24 * 60 * 60 * 1000L;
  } else {
    return 0L;
  }
}

18.2    重构后

public class Unit {
  private static final long SECOND_MILLIS = 1000;
  private static final long MINUTE_MILLIS = 60 * SECOND_MILLIS;
  private static final long HOUR_MILLIS = 60 * MINUTE_MILLIS;
  private static final long DAY_MILLIS = 24 * HOUR_MILLIS;
  private static final long WEEK_MILLIS = 7 * DAY_MILLIS;
  private static final long MONTH_MILLIS = 30 * DAY_MILLIS;
  private static final long YEAR_MILLIS = 365 * DAY_MILLIS;
  private static final long CENTURY_MILLIS = 100 * YEAR_MILLIS;

  static Map<String, Unit> units = new HashMap<String, Unit>();

  public static final Unit SECOND = new Unit(SECOND_MILLIS, "SECOND");
  public static final Unit MINUTE = new Unit(MINUTE_MILLIS, "MINUTE");
  public static final Unit HOUR = new Unit(HOUR_MILLIS, "HOUR");
  public static final Unit DAY = new Unit(DAY_MILLIS, "DAY");
  public static final Unit WEEK = new Unit(WEEK_MILLIS, "WEEK");
  public static final Unit MONTH = new Unit(MONTH_MILLIS, "MONTH");
  public static final Unit YEAR = new Unit(YEAR_MILLIS, "YEAR");
  public static final Unit CENTURY = new Unit(CENTURY_MILLIS, "CENTURY");

  static {
    units.put(SECOND.name, SECOND);
    units.put(MINUTE.name, MINUTE);
    units.put(HOUR.name, HOUR);
    units.put(DAY.name, DAY);
    units.put(WEEK.name, WEEK);
    units.put(MONTH.name, MONTH);
    units.put(YEAR.name, YEAR);
    units.put(CENTURY.name, CENTURY);
  }

  private long millis;
  private String name;

  private Unit(long millis, String name) {
    this.millis = millis;
    this.name = name;
  }

  public long getMillis() {
    return millis;
  }

  public String getName() {
    return name;
  }

  public String toString() {
    StringBuffer buffer = new StringBuffer();
    buffer.append(this.getName());
    buffer.append("[");
    buffer.append(this.getMillis());
    buffer.append("]");
    return buffer.toString();
  }
}

public long toMilliseconds(Unit unit) {
  return unit.getMillis();
}

19    替换switch结构
19.1    重构前

public boolean isLeap(int year) {
  return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

public static int getMonthDays(int year, int month) {
  int numberDays = 0;

  switch (month) {
    case 1:
    case 3:
    case 5:
    case 7:
    case 8:
    case 10:
    case 12:
      numberDays = 31;
      break;

    case 4:
    case 6:
    case 9:
    case 11:
      numberDays = 30;
      break;

    case 2:
      numberDays = isLeap(year) ? 29 : 28;
      break;
  }

  return numberDays;
}

19.2    重构后

public boolean isLeap(int year) {
  return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

private int getFebruaryDays(int year) {
  return this.isLeap(year) ? 29 : 28;
}

public int getMonthDays(int year, int month) {
  int[] months = new int[] { 31, this.getFebruaryDays(year), 31, 30, 31, 30,
                31, 31, 30, 31, 30, 31 };

  return months[month];
}

20    避免对参数赋值
20.1    重构前

public Date getStartTime(Date date) {
  date.setMinutes(fromMinute);
  date.setDate(fromHour);
  date.setDate(fromHour);
  date.setSeconds(0);

  return date;
}


20.2    重构后

public Date getStartTime(final Date date) {
  Calendar calendar = Calendar.getInstance();
  calendar.setTime(date);
  calendar.set(Calendar.HOUR_OF_DAY, fromHour);
  calendar.set(Calendar.MINUTE, fromMinute);
  calendar.set(Calendar.SECOND, 0);

  return calendar.getTime();
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
/* * 原始需求背景: * 网宿CDN要按月收取客户的服务费用,根据流量的大小、 * 服务的类型等,收取不同的费用,收费规则如下: * web应用:1000元/M * 流媒体应用:1000元/M*0.7 * 下载应用:1000元/M*0.5 * 月末打印报表时,要罗列每个用户每个频道的费用、客户总费用, * 还要打印该客户的重要性指数,重要性指数=网页流/100+下载流量/600; * * 需求变更场景: * 系统已经开发出来了,接下来,运维部门现在希望对系统做一点修改, * 首先,他们希望能够输出xml,这样可以被其它系统读取和处理,但是, * 这段代码根本不可能在输出xml的代码中复用report()的任何行为,唯一 * 可以做的就是重写一个xmlReport(),大量重复report()中的行为,当然, * 现在这个修改还不费劲,拷贝一份report()直接修改就是了。 * 不久,成本中心又要求修改计费规则,于是我们必须同时修改xmlReport() * 和report(),并确保其一致性,当后续还要修改的时候,复制-黏贴的问题就 * 浮现出来了,这造成了潜在的威胁。 * 再后来,客服部门希望修改服务类型和用户重要性指数的计算规则, * 但还没决定怎么改,他们设想了几种方案,这些方案会影响用户的计费规则, * 程序必须再次同时修改xmlReport()和report(),随着各种规则变得越来越复杂, * 适当的修改点越 来越难找,不犯错误的机会越来越少。 * 现在,我们运用所学的OO原则和方法开始进行改写吧。 */

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值