DEV Community

loading...

How using OOP improves code quality? Classes vs. Functions

Romany Ghoubrial
・2 min read

Every codebase, be it for a small or a huge system, is a story to tell that takes input, and computes an output. One pillar of quality code is that it is easy to follow through from input to output, much like reading through a script. Everyone wants this, huh?

But it is not always easy, sometimes, you need to write a function to manipulate a global variable—outside the scope of the function—introducing side-effects, let's see how this ruins code readability:

let someVar = 1;

// Define and call a few functions

(function() {
  // Change the state of the global variable
})();

(function() {
  // Do something but not changing someVar
})();

(function() {
  // One more that changes the state of the global variable
})();

console.log(someVar)
Enter fullscreen mode Exit fullscreen mode

As you might have noticed, functions can change the global state, so you have to read through the above three functions to debug the value of someVar, even though the second function didn't change the state of the global variable, but who knows, it could have.

This affects the maintainability of our code as it becomes harder to trace what functions change the global state, and what don't. So it is not easy to follow some variable from input to output, which is what defines quality code.

The solution is to encapsulate data and functions together in the same data structure that also doesn't have visibility to the global state:

class SomeClass {
  let someVar;

  constructor(someVar) {
    this.someVar = someVar
  }

  dummy1() {
    // Change the state of the global variable
  }

  dummy2() {
    // Change the state of the global variable
  }
}

let someVar = new SomeClass(1);
someVar.dummy1()
someVar.dummy2()
Enter fullscreen mode Exit fullscreen mode

This improves code readability as we need to intentionally call the functions that change someVar from inside the data structure itself, I mean, calling someVar.dummy1() and someVar.dummy2() in the above example.

Discussion (0)