zoukankan      html  css  js  c++  java
  • 31天重构学习笔记5. 提升字段

    概念:本文中的提升字段和前面的提升方法颇为相似,就是把子类公用的字段提升到基类中,从而达到公用的目的。

    正文:如下代码所示, Account 的两个子类CheckingAccount SavingsAccount 都有minimumCheckingBalance 字段,所以可以考虑把这个字段提到基类中。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace LosTechies.DaysOfRefactoring.PullUpField.Before
    {
    public abstract class Account
    {
    }

    public class CheckingAccount : Account
    {
    private decimal _minimumCheckingBalance = 5m;
    }

    public class SavingsAccount : Account
    {
    private decimal _minimumSavingsBalance = 5m;
    }
    }

    重构后的代码如下,这样提的前提是这些子类有一个基类或者有很多相似的字段和方法,不然为了一个字段而单独建立一个抽象类是不可取的,所以这个就需要具体权衡。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace LosTechies.DaysOfRefactoring.PullUpField.After
    {
    public abstract class Account
    {
    protected decimal _minimumBalance = 5m;
    }

    public class CheckingAccount : Account
    {
    }

    public class SavingsAccount : Account
    {
    }
    }

    总结:这个重构的策略比较简单,同时也是比较常用的一些做法,最主要就是要注意权衡是否真的有这个必要,看这样做究竟有没有什么好处(比如只需要改一个地方,维护简便了,同时代码量也更少了等)。

  • 相关阅读:
    响应式css样式
    组件 computed 与 vuex 中 getters 的使用,及 mapGetters 的使用,对象上追加属性,合并对象
    nginx 错误集锦
    动态的添加路由
    NProgress的使用 及 路由 token 定向的使用
    token的解码及 判断值不为空的方法
    nginx 的使用
    IT公司100题-tencent-打印所有高度为2的路径
    测试
    Objective-C 与 C++ 的异同
  • 原文地址:https://www.cnblogs.com/ywsoftware/p/2892570.html
Copyright © 2011-2022 走看看