http://www.altdevblogaday.com/2012/04/26/functional-programming-in-c/
这个在《程序员》杂志上有译文,也很不错。
functional programming is good
卡马克根据自己的实践得出的结论是,软件开发过程中的很大一部分的不足来自开发者对于自己程序将会运行于哪些可能的状态(state)认识不足,而这样的认识不足导致的问题在多线程并行环境中会被扩大化。
而过程式编程倾向于将程序中的state明显化,这样我们就更容易有充足的认识,相比而言,OO编程则很容易把state的转换给封装起来,让我们对state的控制和认识变得更难。
c++并不鼓励functional programming,但是也不禁止,而且还赋予了我们很多底层编程能力,这也是c++黑很多,但是绝大多数的高品质游戏还是由c++写的原因所在。
Pure Function
carmack定义了一个pure function,这是一个很有意义的抽象(尽管它不存在),pure function只关注传入的参数,然后返回一个或多个基于参数的结果。
并且它:
- 不维护自己的内部状态
- 不和全局数据做交互(读或者写),不做IO
- 不修改参数
读到这部分的时候,我已经很明显的感觉到这样的pure function的简洁和强大了,它有这样的强力属性:
- 易于重用
- 易于测试---由于不依赖很多东西,传入一个值,那么返回值是一定的
- 易于维护和理解
如果只是不用考虑长远的处理问题,那么怎么方便怎么搞,但是如果你是想写一个在多年后仍旧很有战斗力的代码,那么还是深思熟虑的好,比如写一些纯函数,而不是很随意的读写全局变量。
而实践中显然会有相当的情况,让我们很难甚至无法使用pure function来搞定问题,carmack认为不能绝对纯,但是尽可能纯,也会大幅度的提高代码质量,并且把烂代码弄得比较纯性价比颇高,而做到绝对纯则常常是边际效应递减的很厉害。
而代码质量对代码的未来有巨大的决定作用,代码质量差,会把项目自己拖入沼泽,最后死了拉到。
而到object oriented programming中来看,const是有着很大的设计意义,有const的成员函数在维护内部状态方面仍旧可以认为是纯的。
效率与实践
一般来说,效率和生产力是此消彼长的矛盾的,使得我们不得不常常打破纯函数这样的实现。
实践中,carmack建议关注state的变换,如果可以的话,让函数返回一份copy而不是自己修改自己(比如vector的normalize),尽可能在可以使用const的地方使用const。