Object Oriented Vs Functional Programming

Object Oriented Vs Functional Programming

JavaScript allows for both object oriented and functional programming styles of coding.

In this article, we'll briefly go through what each of these paradigms entail, where and why to use each of these coding styles.

1. Object Oriented Programming

Object Oriented Programming is a programming paradigm based on the concepts of objects. Objects represent things that the program is about.

For example: If one were to write a program to calculate the average score and grade students in a class. The students will be the objects, i.e. what the program is about.

An object has attributes (properties/characteristics) and methods (functions to access and manipulate these attributes) therefore, kind of 'mimicking' the real world, and this is what gives this programming paradigm a real edge in contrast to the other coding styles.

2. Functional Programming

Whereas object oriented programming is based on objects, functional programming is based on functions, pure functions.

What exactly is a pure function then?

A function is a set of statements performing a task; typically taking an input and returning a value, as an output. For a function to be considered pure, it has to have the following three main characteristics:

  1. Same value inputs will always return the same value outputs. That is to mean, the value returned by the function always depends on the input only.
  2. No side effects. Pure functions are completely independent of the outside state. Calling these functions do not interfere with the outside state in any way. One way of telling if a function interferes with the outside state is if the function can be called without using its return value. Such functions are considered impure.
  3. Immutability. The data passed onto the function is not altered in any way at all. A copy of the passed data is created to be used, manipulated and altered by the function, thus avoiding altering the passed data and interfering with the outside state.

Which of the two paradigms is better?

Where to use what paradigm is entirely dependent on what is to be achieved.

In object oriented programming the concept of classes and objects makes it easier to manage and manipulate data, whereas in functional programming the strict separation of data and methods leads to less errors compared to object oriented programming.

Conclusion

Therefore, if the goal is data encapsulation (hiding of data and information; keeping the data secure from unwanted external usage and manipulation) then object oriented programming is the way to go. And, in cases whereby there are a lot of operations to be performed on fixed data, functional programming is preferred.

Even better yet, combine both paradigms to benefit on the advantages of each of these paradigms.

Any thoughts and comments, would love to hear those!