Thursday, December 10, 2009

Functions and Objects - Computer Science Week

You may have heard of object oriented programming, in phrases like "java is an object oriented language". Fewer people have heard of functional programming. But what do these terms mean? They represent two extremes in the way we look at computing.

In general we think of computing as data and things you do to data to change it. Like in English we have nouns and verbs. You can think of object oriented programming as a language with only nouns, and functional programming as a language without nouns. You'd think neither system was workable, but in practice, they are two (radically) different ways of thinking about the same thing (data, and ways to change it).

Object oriented programming makes data the king, in the form of an "object". Objects know how to change their state, and you simply send them messages about what to do. For instance, in an object oriented programming language, "1" is not data, it's an object. "1 + 2" sends the object "1" a message to add "2" to itself (of course giving "3" as the resulting object). Object oriented programming's strength is that objects are self contained, so it is easier to write a program without having to consider what every part of it does. You can trust that the objects know what they're doing (if they are written correctly).

In functional programming we do away with the notion of data completely. Everything's a function, just like in math class. "1" is not data again, it's a function (that always returns "1"). The big strength of functional programming is that there are no "side effects". In other words, without data, a function always returns the same result with the same inputs. That makes it possible to reason about a program and mathematically prove whether it is correct or not.


Post a Comment