正经文章的地方

函数式编程

什么是函数式编程

  • 随着React的火热开始流行
  • 纯函数 vs 不纯的函数
  • 对于同样的输入x,y=f(x)能得到唯一的结果则是纯函数
  • 反例:
  • 大致有两种:
    • 会修改参数本身的,例如pop、splice
    •  依赖外部参数的,例如下例

var a = [1, 2, 3, 4, 5];

function test() {
	// pop不是纯函数,test也不是
	return a.pop();
}
  • 不纯函数的副作用
    • 太复杂了,对于复杂系统,只看函数本身根本无法判定最后结果是什么
    • 调试 or 定位问题不方便,函数结果不对时需要排查问题的范围会被扩散

函数式 vs 面向对象

  • 例子:
    • 场景一:某五星级宾馆提供开房服务,房间提供室内游泳服务、晚餐服务、睡觉服务,某富二代来开房,某艺术家来休假

var HotelRoom = function() {
	this.options = {
		// 默认配置
		hasPool: true,
		poolIndoor: true
	}
};

HotelRoom.prototype.swim = function() {
	var options = this.options;
	if (options.hasPool) {
		if (options.poolIndoor) {
			return ('You can swim indoor');
		} else {
			return ('You can only swim outdoor');
		}
	} else {
		return ('We have no pools');
	}
}
HotelRoom.prototype.dinner = function() {
	return ('You can have dinner');
}
HotelRoom.prototype.sleep = function() {
	return ('You can sleep well');
}

var fu2dai = new HotelRoom();
var artiest = new HotelRoom();
  • 场景二:富二代不满意,表示还要想剪杀马特发型,艺术家也不满意,表示想要给自己新画的画装裱一下,酒店经理:黑人问号脸???你们想要我们干啥?

HotelRoom.prototype.swim = function() {
	// 游泳...
}
HotelRoom.prototype.dinner = function() {
	// 吃饭...
}
HotelRoom.prototype.sleep = function() {
	// 睡觉...
}
HotelRoom.prototype.cutShamate = function() {
	return ('Ok, cut your hair here');
}
HotelRoom.prototype.mountWork = function() {
	return ('fine, mount your work here');
}
  • 场景三:富二代继续不满意,他还要做马杀鸡 => 修指甲 => 各种新想法新需求

HotelRoom.prototype.swim = function() {
	// 游泳...
}
HotelRoom.prototype.dinner = function() {
	// 吃饭...
}
HotelRoom.prototype.sleep = function() {
	// 睡觉...
}

var fu2daiGoBuy = function(cloth) {
	return function(hair) {
		console.log(cloth + ' match your style ');
		return function(nail) {
			console.log(hair + ' and ' + nail + ' give you a new yourself');
		}
	}
}

fu2daiGoBuy('rock-jacket')('shamate hairstyle')('black nail');

var artiestGoBuy = function(wood) {
	return function(frame) {
		frame.type = wood;
		return function(picture) {
			picture.frame = frame;
			return picture;
		}
	}
}

var picture = {
	picture: '反正很艺术的画'
};
var frame = {
	name: '高级画框'
};
artiestGoBuy('红木')(frame)(picture);
  • 富二代买东西做发型(艺术家装裱画作)的场景,既和hotel没啥关系,又不属于功能型的,对于富二代来说是注重的结果,最后出来的是什么,我需要投入进去的是什么,而且这些功能点相对独立,在测试的时候也需要关注输入和输出的对应性。

函数式编程的好处

  • 过程好理解
  • 便于修改
  • 依赖明确,不会依赖外部环境
  • 声名式(结果是什么)
  • 便于debug和管理

面向对象编程的好处

  • 场景感强
  • 复杂业务功能的管理
  • 指令式(做什么)

参考文献