Tuesday, January 5, 2016

Pitfalls of Object Oriented Programming

As I try to understand Javascript as a language one of the things which I need to unlearn is Object Oriented Programming. With Ecmascript 6 and tools like TypeScript from Microsoft, so far I have managed to write a lot of object oriented programs in Javascript which essentially is a functional language. 
So first thing which I need to do is unlearn OOPS. Here are a few pitfalls of OOPS : 

1) A Class is a collection of Data and Methods which operate on this data. As a programmer trying to learn OOPS this was very unintuitive, but once you start practicing OOPS, it becomes the obvious choice and all the apprehensions like why exactly should I keep my data definitions and  Functions together goes away. Going back to my learning days, I once again find it unintuitive. 

2) The way a function behaves in a class can be totally dependent on the state of the object which can be hidden from the consumer of the class. e.g. I can easily write a class which like 
public class Calci{
    private var toggle = false;
    public int Add(a,b){
        toggle = ! toggle;
        if(toggle) return a + b;
        return a - b;
The behavior of method Add totally depends on a the state of the Calci object which is hidden from the consumer. So understanding what a method does in object oriented program can be tricky sometimes. Although this is an advantage when compared to Procedural language where the behavior of the function can be dictated by a global variable which is declared somewhere in a different file. But then I have visibility in the scope and if I try it hard I can figure it out. 

3) No Class Hierarchy is correct : No matter how much thought one gives into create a right class hierarchy. One does end up in a situation where the hierarchy is not correct. This is one of the major reasons for refactoring the code while developing projects. As the code size grows it becomes rather difficult to refactor as the change impacts all the ecosystem. 

4) You get a lot of rings and bells attached with any class which you choose to reuse. e.g. If I derive from a Car class I get the method Drive for free even though I may not want to drive an auto-drive car. 

As one learns javascript one should ensure that we don't fall back on the knowledge we acquired while learning OOPS and try to apply them in this new paradigm. Next up is to figure out what kind of inheritance is possible in javascript, how we can use it, and how it differs from classical inheritance of OOPS.

No comments: