Java编程思想(04)——重构让代码更简洁(四)

本文介绍了四种Java重构方法以提升代码质量:使用类替换类型代码,将参数对象化,封装集合操作以减少冗余,避免一次性变量并确保每个变量单一职责。通过这些重构实践,代码变得更加清晰和易于维护。
摘要由CSDN通过智能技术生成

使用类替换类型代码

重构前

public class LabelComparator implements Comparator, Serializable {

  private static final long serialVersionUID = 1L;

  public static final int ASC = 1;
  public static final int DESC = 2;

  private int sortType = ASC;

  public LabelComparator() {
  }

  public LabelComparator(int sortType) {
    this.sortType = sortType;
  }

  public int compare(Object o1, Object o2) {
    if (o1 == null && o2 == null) {
      return 0;
    }
    if (o1 == null) {
      return -1;
    }
    if (o2 == null) {
      return -1;
    }

    if (((Label) o1).getIndex() < ((Label) o2).getIndex()) {
      return (sortType == ASC) ? -1 : 1;
    } else if (((Label) o1).getIndex() > ((Label) o2).getIndex()) {
      return (sortType == ASC)  ? 1 : -1;
    } else {
      return 0;
    }
  }
}

重构后

public final class SortMode implements Serializable {

  private static final long serialVersionUID = 1L;

  private static final Map<String, SortMode> INSTANCES = new HashMap<String, SortMode>();

  private final int type;
  private final String name;

  private SortMode(int type, String name) {
    this.type = type;
    this.name = name;
  }

  public String toString() {
    return name;
  }

  public static final SortMode ASC = new SortMode(1, "ASC");

  public static final SortMode DESC = new SortMode(2, "DESC");

  static {
    INSTANCES.put(ASC.name, ASC);
    INSTANCES.put(DESC.name, DESC);
  }

  public boolean isAsc() {
    return ASC.type == this.type;
  }

  public boolean isDesc() {
    return DESC.type == this.type;
  }

  private Object readResolve() {
    return INSTANCES.get(name);
  }

  public static SortMode parse(String name) {
    return (SortMode) INSTANCES.get(name);
  }
	
  public boolean equals(Object obj) {
    if (obj instanceof SortMode) {
      SortMode that = (SortMode) obj;
        if (that.type == this.type) {
          return true;
        }
        return false;
    } else {
      return false;
    }
  }
}

public class LabelComparator implements Comparator, Serializable {

  private static final long serialVersionUID = 1L;
  public SortMode mode = SortMode.ASC;

  public LabelComparator() {
  }

  public LabelComparator(SortMode mode) {
    this.mode = mode;
  }

  public int compare(Object o1, Object o2) {
    if (o1 == null && o2 == null) {
      return 0;
    }
    if (o1 == null) {
      return -1;
    }
    if (o2 == null) {
      return -1;
    }

    if (((Label) o1).getIndex() < ((Label) o2).getIndex()) {
      return mode.isAsc() ? -1 : 1;
    } else if (((Label) o1).getIndex() > ((Label) o2).getIndex()) {
      return mode.isAsc() ? 1 : -1;
    } else {
      return 0;
    }
  }
}


对象封装参数

重构前

public int getRemainMinutes(int hour, int minute, 
                         int fromHour, int fromMinute
                         int toHour, int toMinute) {
  // --------from-------to--------position-------
  int startHour = toHour;
  int startMinute = toMinute;
  
  if (this.fromAfterEqual(hour, minute)) {
    // ------position------from-------to--------
    startHour = fromHour;
    startMinute = fromMinute;
  } else if (this.toAfterEqual(hour, minute)) {
    // ------from-------position------to--------
    startHour = hour;
    startMinute = minute;
  }

  return this.getMinutes(startHour, startMinute, toHour, toMinute);
}

重构后

public class DayPart implements Serializable {

  int fromHour = -1;
  int fromMinute = -1;
  int toHour = -1;
  int toMinute = -1;

  public int getFromHour() {
    return fromHour;
  }

  public void setFromHour(int fromHour) {
    this.fromHour = fromHour;
  }

  public int getFromMinute() {
    return fromMinute;
  }

  public void setFromMinute(int fromMinute) {
    this.fromMinute = fromMinute;
  }

  public int getToHour() {
    return toHour;
  }

  public void setToHour(int toHour) {
    this.toHour = toHour;
  }

  public int getToMinute() {
    return toMinute;
  }

  public void setToMinute(int toMinute) {
    this.toMinute = toMinute;
  }
}

public int getRemainMinutes(int hour, int minute, DatePart datePart) {
  int fromHour = datePart.getFromHour();
  int fromMinute = datePart.getFromMinute();
  int toHour = datePart.getToHour();
  int toMinute = datePart.getToMinute();

  // --------from-------to--------position-------
  int startHour = toHour;
  int startMinute = toMinute;
  
  if (this.fromAfterEqual(hour, minute)) {
    // ------position------from-------to--------
    startHour = fromHour;
    startMinute = fromMinute;
  } else if (this.toAfterEqual(hour, minute)) {
    // ------from-------position------to--------
    startHour = hour;
    startMinute = minute;
  }

  return this.getMinutes(startHour, startMinute, toHour, toMinute);
}


封装集合操作

重构前

public Class Group{

  private List<User> userList = new ArrayList<User>();

  public void setUserList(List<User> userList){
    this.userList = userList;
  }

  public List<User> getUserList(){
    return this.userList;
  }
}

重构后

public Class Group{

  private List<User> userList = new ArrayList<User>();

  public void setUserList(List<User> userList){
    this.userList = userList;
  }

  public List<User> getUserList(){
    return this.userList;
  }

  public void addUser(User user){
    this.getUserList().add(user);
    user.setGroup(this);
  }

  public void removeUser(User user){
    this.getUserList().remove(user);
    user.setGroup(null);
  }
}


避免一次性变量

重构前

public int countWeekDay(Month month, WeekDay weekDay) {
  int count = 0;
  int[][] weeks = this.getDates()[month.getMonth()];
    for (int week = 0, weekLen = weeks.length; week < weekLen; week++) {
      int date = weeks[week][weekDay.getDay()];
      if (date > 0) {
        count++;
      }
    }

  return count;
}

重构后

public int countWeekDay(Month month, WeekDay weekDay) {
  int count = 0;
  int[][] weeks = this.getDates()[month.getMonth()];
  for (int week = 0, weekLen = weeks.length; week < weekLen; week++) {
    if (weeks[week][weekDay.getDay()] > 0) {
      count++;
    }
  }

  return count;
}

一个变量一种作用

重构前

public IPolyDate getIndexWeekDay(Month month, int index, WeekDay weekDay) {
  int count = this.countWeekDay(month, weekDay);
  if (index > count) {
throw new ExceedMaxWeekIndexOfMonthException("Arguement index[" + 
index + "] exceeds max week index[" + 
count + "] of month[" + month.toString() + "].");
  }

  count = 0;
  int[][] weeks = this.getDates()[month.getMonth()];
  for (int week = 0, weekLen = weeks.length; week < weekLen; week++) {
    int date = weeks[week][weekDay.getDay()];
    if (date > 0) {
      if (++count == index) {
        return new PolyDate(year, month.getMonth(), date);
      }
    }
  }

  return null;
}

重构后

public IPolyDate getIndexWeekDay(Month month, int index, WeekDay weekDay) {
  int maxCountOfWeekDay = this.countWeekDay(month, weekDay);
  if (index > maxCountOfWeekDay) {
throw new ExceedMaxWeekIndexOfMonthException("Arguement index[" + 
index + "] exceeds max week index["+ 
maxCountOfWeekDay + "] of month[" + month.toString() + "].");
  }

  int count = 0;
  int[][] weeks = this.getDates()[month.getMonth()];
  for (int week = 0, weekLen = weeks.length; week < weekLen; week++) {
    int date = weeks[week][weekDay.getDay()];
    if (date > 0) {
      if (++count == index) {
        return new PolyDate(year, month.getMonth(), date);
      }
    }
  }

  return null;
}


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值