RefactoringPull Up /Push Down Method or Field

// 重构前代码说明:
//Pull Up Method
//Pulling it up in the inheritance chain when a method needs to be used by multiple implementers

    
    
/// <summary>
    
/// 交通工具
    
/// </summary>
    public abstract class Vehicle
    {
       
// other methods
    }


    
/// <summary>
    
/// 小车
    
/// </summary>
    public class Car : Vehicle
    {
        
public void Turn(Direction direction)
        {
             
// code here
        }
     }

    
/// <summary>
    
/// 摩托车
    
/// </summary>
     public class Motorcycle : Vehicle
     {

     }

    
/// <summary>
    
/// 方向
    
/// </summary>
     public enum Direction
     {
         Left,
         Right
     }

重构后代码:

代码
    /// <summary>
    
/// 交通工具
    
/// </summary>
    public abstract class Vehicle
    {
        
public void Turn(Direction direction)
        {
            
// code here
        }
    }

/// <summary>
    
/// 小车
    
/// </summary>
    public class Car : Vehicle
    {
        
// other methods
    }

    
/// <summary>
    
/// 摩托车
    
/// </summary>
     public class Motorcycle : Vehicle
     {
         
// other methods
     }

    
/// <summary>
    
/// 方向
    
/// </summary>
     public enum Direction
     {
         Left,
         Right
     }

看上去很自然,但有时候在实际code的时候,新增,修改过程中却往往容易破坏这个规则。

同样,只在继承链的一个子类中使用的方法,就要考虑push down 了!

代码
// 重构前代码说明:
//Push Down Method
//Push it Down in the inheritance chain when a method only one sub-class to be used by implementer

    
    
public abstract class Animal
    {
        
//犬吠
        public void Bark()
        {
        
//很明显其他动物是不会吠的,only dog
        
// code to bark
        }
    }

     
public class Dog : Animal
     {
     }

     
public class Cat : Animal
     {
     }

这样重构也很自然了,注:当一个抽象类没有任何方法的时候你是否考虑将其转换到接口?没有任何方法和属性的接口即标识接口(marker interface)。标识接口没有具体语义,只是对统一类对象的一个标识却没有相同的方法,方便framework基本的统一处理。

方法的pull和push就这么简单和自然了,字段当然也是,只是这个意识需要加强。

原文地址:https://www.cnblogs.com/buaaboyi/p/1957589.html