12/11/2005

 

Different Attitudes Towards Side-Effect

Originally posted at: http://www.bloglines.com/blog/taowen?id=6 Revision:2005/12/19 Modified the way to describe. Added material related to monad. As a well known fact, one fundamental distinction between FP(Functional Programming) and IP(Imperative Programming) is the way the two treat the side-effect. FP is based on the theory of lambda calculus whose η-conversion rejects the existence of side-effect. So when programming in FP language, you were suggested to write the codes in a stateless way. IP actually is built upon the side-effect. Without side-effect, a command computed means nothing. But in real world, the FP language can not be "ALL" pure. Because at least the I/O operation involves side-effect. So, every FP language had to give a answer to the question - "How to interact between stateful and stateless world". In old-fashioned FP language, such as scheme, it just allows the exsitence side-effect by magic like "set!". Haskell, which is much more modern, uses the monad from the category theory to attack this problem. I have to say I haven't understood the theory fully, but it gave me some impression that it is no more than another way to write imperative code, then you can write both style codes in one language, and the typing system guarantee the beautiful functional core won't be messed up by the monadic actions. So, I think the general attitude in FP world is to narrow the side-effect in the very skin of the program, leaving the core full functional. During a discussion with Vincent Xu, I realized the fact OOP(object-oriented programming) actually is a try to ease the pain of side-effect in IP. It uses objects to wrap around the side-effect, and expose semantic clear interface to transform the states. As long as the objects handle its state in a consistent way, side-effect won't be that harmful. Vincent Xu told me in smalltalk, the object is much bigger than it is in Java. In Java, we prefer XMLWriter.write(obj) to obj.writeAsXML(writer). According to his understanding, in smalltalk we should tell instead of ask, i.e. in this case XMLWriter.write(obj), the XMLWriter has to ask the obj for its state, but if we use obj.writeAsXML(writer), the obj is telling the writer its state instead of being asked. So, if we keep all code well object-oriented, i.e. tell instead of ask, we may achieve the goal of OOP by wrapping all the side-effects by objects. Generally speaking, I prefer OOP over FP. It may majorly because I don't know much about FP. But another important reason is I feel like can't writting all things in a stateless way. Once the program is not pure functional, I am freaked out by the fact. So, the side-effect bothers me a lot which stopped me from working with FP languages as a result.

Comments: Post a Comment

Subscribe to Post Comments [Atom]





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]