Eclipse重构——Move Field

Motivation

如果某个field,在其所驻class之外的另一个class中有更多的函数使用了它,那么可以考虑将这个field移动到另一个class。

Mechanics

1  如果field属性为public,应该先使用EncapsulateField或者Self Encapsulate Field封装该成员。

2  在target class中建立该field,同时应用SelfEncapsulate Field建立set/get函数。

3  在source class中新建引用targetclass对象的成员。将所有对source field的引用,替换为对target class中该field的set/get函数的调用。(要同时处理子类)

删除source field。


Eclipse refactor菜单默认提供了[Move]选项,但是直接Move Field并不会自动更改对该Field的reference。因此实际需要绕一圈。 [Encapsulate] field +  copy + [Inline]

// 重构之前的代码,需要move _interestRate
public class Account …
    private final double _interestRate= 1.0;
    private AccountType _type;
    double interestForAmount_days(double amount, int days) {
        return _interestRate * amount * days / 365;
    }


/1. /对Field "_interestRate",应用[Encapsulate]

publicclassAccount …

privatefinaldouble_interestRate= 1.0;

    private AccountType _type;

    double interestForAmount_days(double amount,int days) {

       return get_interestRate() * amount * days / 365;

    }

    privatedoubleget_interestRate() {

       return_interestRate;

    }

//2. 将"_interestRate" 定义,包括get/set直接复制到目标类。(是直接复制,而不是move 重构)

class AccountType ...

    private final double _interestRate= 1.0;

    private double get_interestRate() {

        return_interestRate;

    }

//3. 将源类中的get/set重新实现为委托给目标类的get/set

public class Account ...

    private final double _interestRate= 1.0;

    double get_interestRate() {

        return _type.get_interestRate();

    }

// 4. 删除源类中的Field " _interestRate" ,应用[Inline]替换get/set为委托给_type

publicclass Account {

    private finaldouble_interestRate = 1.0;

    doubleget_interestRate() {

        return_type.get_interestRate();

}

    private AccountType_type;

    double interestForAmount_days(double amount,int days) {

        return_type.get_interestRate() * amount * days / 365;

    }

 

如果有更简单的方法,欢迎分享


上面源码可以在 here 获取。



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值