Functional v OOP
11/14/14 (technical)

What’s the difference between Functional and Object Oriented Programming (OOP)? The question comes up quite frequently and can be somewhat bewildering, especially to a novice programmer. There are a lot of good reasons you could be asking this question, but if you’re new to field such as myself, the reason your probably asking is because you want to have a cursory understanding of the difference between the two and calm some fear that you are learning the "wrong" way to program.

Let’s start with a high level discussion of programming languages. Languages, "are notation...a program is a formal description of the problem you want a computer to solve" (link). All programming languages are universal languages capable of solving any problem. Some languages are object oriented, some are functional and many include elements of both, but the difference is a matter of notation, not, in a strictly speaking sense, of capability. Although, different notation can make certain problems easier or harder to solve. Some of the most successful languages, like Ruby and Scala, combine elements of both programming styles.

Now let’s take a look at what this difference actually looks like in practice. At Dev Bootcamp, you first learn OOP, so you should already have a good sense of what that looks like. In OOP, the world is composed of Objects that interact with each other. In functional programming, the world is composed of, wait for it, functions, just like you learned about in math class, where one input gives you one output. Thus, functional programming avoids state and mutable data. Let’s look at some concrete examples (borrowed from here).

Appending Arrays

OOP:

indexes = [1, 2, 3]
indexes << 4
indexes # [1, 2, 3, 4]

Functional:

indexes = [1, 2, 3]
all_indexes = indexes + [4] # [1, 2, 3, 4]
Updating Hashes

OOP:

hash = {:a => 1, :b => 2}
hash[:c] = 3
hash

Functional:

hash = {:a => 1, :b => 2}
new_hash = hash.merge(:c => 3)
Updating Strings

OOP:

string = "hello"
string.gsub!(/l/, 'z')
string # "hezzo"

Functional:

string = "hello"
new_string =  string.gsub(/l/, 'z') # "hezzo"

So what are the examples of Function Programming? By avoiding state and mutable data, it can be argued that Functional Programming produces cleaner code and offers referential transparency, which is to say an expression can be replaced by its values. Such referential transparency opens up the door to some exciting possibilities (again borrowed from here).

So if you’re novice programmer, you can start to think about situations when Functional Programming principles could be incorporated, even if you live in object oriented world.

Cheers!

Additional Resources: