zoukankan      html  css  js  c++  java
  • 重构第5天:提升字段(Pull Up Field)

    理解:提升字段和前面讲解的方法提公很类似,可以说方式都是一样的。就是把继承类中经常用到的字段,提出来 放到基类中,达到通用的目的。提高代码重用性和可维护性。

    详解:如下重构前的代码:

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 
     6 namespace _31DaysRefactor
     7 {
     8 
     9     public abstract class Account
    10     {
    11 
    12     }
    13 
    14     public class CheckingAccount : Account
    15     {
    16         private decimal _minimumCheckingBalance = 5m;
    17     }
    18 
    19     public class SavingsAccount : Account
    20     {
    21 
    22         private decimal _minimumCheckingBalance = 5m;
    23     }
    24 }

    从代码乐意看出,Account类的继承类CheckingAccount和SavingsAccount都有一个相同的字段_minimumCheckingBalance ,为了提高易用性和可维护性,我们把_minimumCheckingBalance 字段提出来放到基类Account中去。

    重构后的代码:

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 
     6 namespace _31DaysRefactor
     7 {
     8 
     9     public abstract class Account
    10     {
    11         protected decimal _minimumCheckingBalance = 5m;
    12     }
    13 
    14     public class CheckingAccount : Account
    15     {
    16         
    17     }
    18 
    19     public class SavingsAccount : Account
    20     {
    21 
    22         
    23     }
    24 }

    注意提到公共基类中,最好用 protected 关键字来修饰,表示只能被自身和子类使用。重构其实就这么简单。

  • 相关阅读:
    jQuery实现每隔几条元素增加1条线的方法
    Unity3D for Mac 破解
    IOS
    Unity3D 动态地创建识别图
    Easy AR简单教程
    iOS对象(数组)转化为JSon字符串
    iOS对象(字典或数组)转化为JSon字符串
    iOS
    iOS 逆向
    ios-逆向 手把手安装最新版Theos
  • 原文地址:https://www.cnblogs.com/yplong/p/5285427.html
Copyright © 2011-2022 走看看