Eclipse重构——Separate Query from Modify

《重构——改善既有代码》


Motivation

坚持这样一条原则:任何有返回值的函数,都不应该有看得到的副作用。所以查询和修改必须分开。

Mechanics

ü  新建一个查询函数,其返回值与原函数相同;修改原函数,令他调用查询函数,并返回查询结果。

ü  将调用原函数的代码改为调用查询函数。然后在调用查询函数的那一行之前调用原函数。

ü  修改原函数,删除return语句,将原函数返回值改为void。


Eclipse重构菜单中没有直接对应的选项,不过还是可以通过组合命令实现,decompose method + [Inline]。 其核心思想是,先将函数分解为纯粹的查询与 modify 两部分,然后利用内联,将原函数自动替换为上面两个函数。

        // sendAlert是modify部分,  查询people name是query部分
	String foundMiscreant(String[] people) {
		for (int i = 0; i < people.length; i++) {
			if (people[i].equals("Don")) {
				sendAlert();
				return "Don";
			}
			if (people[i].equals("John")) {
				sendAlert();
				return "John";
			}
		}
		return "";
	}

// 1. 分解上面函数为查询和modify两部分,一般可以考虑Extract Method,但往往需要根据理解,分解代码,这里我直接列出结果

	// sendAlert是modify部分,  查询people name是query部分
	String foundMiscreant(String[] people) {
		String name = queryMiscreant(people);
		if(!name.isEmpty()) sendAlert();
		
		return name;
	}

	private String queryMiscreant(String[] people) {
		for (int i = 0; i < people.length; i++) {
			if (people[i].equals("Don")) {
				return "Don";
			}
			if (people[i].equals("John")) {
				return "John";
			}
		}
		return "";
	}

// 2 [Inline] 原函数

String foundMiscreant(String[] people) {

    String name =queryMiscreant(people);

        if(!name.isEmpty()) sendAlert();

        return name;

}


调用原来函数的地方会自动做如下调整:

void checkSecurity(String[] people) {                                          

        String found =foundMiscreant(people);                                 

        someLaterCode(found);

}

                    ||

                    V

void checkSecurity(String[]people) {

        String name = queryMiscreant(people);

        if(!name.isEmpty()) sendAlert();

        String found = name;

        someLaterCode(found);

    }


over

以上源码可以here免费下载


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值