代码重构(一)-用函数对象代替函数(replace method with method object)

本文探讨了代码重构中的一个重要技巧——用函数对象代替过长的函数,以提高代码可读性和维护性。通过实例说明如何进行这样的重构,帮助开发者解决因函数内部局部变量多、引用关系复杂导致的重构难题。
摘要由CSDN通过智能技术生成

在程序开发中程序重构是必须也是必不可少的一个部分。在程序开发工程中我们一向不断的腔调小型的函数,小型函数的可读性高。其中函数过长造成函数的可读性差是我们经常遇到的一个问题,因此代码重构就是一项必不可少的一个环节了。但是在重构过程中我们会越到很多的问题,包含函数内部局部变量多,相互之间有引用关系,从而为函数的拆解提供了很大的不便。为了解决这种问题,我们就提出来一个解决的办法用函数对象代替函数(replace method with method object).不多说直接附上案例;、

原函数:

package test;

public class Account {

	
	public int gamma(int one,int two,int three ){
		return new Gamma(this, one, two, three).compute();
	}
	
	public int delta(){
		return 0;
	}
	
}


根据函数提炼出对应的函数类:
package test;


/**
 * 
 * 重构,以函数对象取代函数
 * 
 * @author jhone
 *
 */
public class Gamma {

	private Account _account;
	private int imp_one;
	private int imp_two;
	private int imp_three;
	private int one;
	private int two;
	private int three;

	
	// 添加构造函数
	public Gamma(Account _account, int imp_one, int imp_two, int imp_th
假设我们现在有一个图形类,其中包含了三种不同类型的图形:矩形、圆形和三角形。这个类使用一个整型变量来表示图形的类型,我们需要使用Replace Type Code with Classes重构手法来改善这个类的设计。 重构前的代码如下: ```c enum ShapeType { Rectangle, Circle, Triangle }; struct Shape { enum ShapeType type; double width; double height; double radius; double base; double height; }; void drawShape(struct Shape* shape) { switch (shape->type) { case Rectangle: // draw rectangle break; case Circle: // draw circle break; case Triangle: // draw triangle break; } } ``` 重构后的代码如下: ```c struct Shape { double width; double height; double radius; double base; double height; }; struct Rectangle { struct Shape shape; }; struct Circle { struct Shape shape; }; struct Triangle { struct Shape shape; }; void drawShape(struct Shape* shape) { // draw shape } void drawRectangle(struct Rectangle* rectangle) { drawShape(&(rectangle->shape)); } void drawCircle(struct Circle* circle) { drawShape(&(circle->shape)); } void drawTriangle(struct Triangle* triangle) { drawShape(&(triangle->shape)); } ``` 通过Replace Type Code with Classes重构手法,我们将图形类分成了三个子类,分别表示矩形、圆形和三角形,每个子类都包含了一个Shape结构体,用来表示图形的属性。同时,我们将原来的drawShape函数拆分成了三个函数,用来分别绘制不同类型的图形。这样做的好处是,可以使代码更加模块化、易于扩展和维护。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值