DEV Community

Discussion on: Functional vs Object Oriented vs Procedural programming

 
efpage profile image
Eckehard

I really appreciate your post, as it is pretty instructive to have a direct comparison. I think it is not helpful to talk about programming paradigms without a task. Here it is clear that it is more a demonstration.

From my experience the three approaches are not mutually exclusive. As classes always are a bit more "expensive" (with respect to code length and brain power), you should use them only where it is necessary or helpful. But to be true, it is never really necessary to use classes, it only may be helpful.

If a class only contains a single function or static data, it´s simply waste of time and memory. OO is no religion, it´s a tool.

So, your code could look like this:

// Class responsible only for creating valid user
class User {
  constructor(username, password) {
    if (username.trim().length < 3)
      throw new Error('Username must be at least 3 characters long')
    if (!password.match(/[0-9]/))
      throw new Error('Password must contain at least one digit')

    this.username = username
    this.password = password
  }
}

// Class responsible only for from handling
class FormHandler {
  logs = []
  constructor(formElement) {
    this.form = formElement
    this.form.addEventListener('submit', this.handleSubmit.bind(this))
  }

  handleSubmit(e) {
    e.preventDefault()
    const username = e.target.elements.username.value
    const password = e.target.elements.password.value

    try {
      const user = new User(username, password)
      console.log(user)
      console.log(this.logs)
    } catch (message) {
        this.logs.push(message)
        alert(message)
    }
  }
}

const form = document.querySelector('form')
new FormHandler(form)
Enter fullscreen mode Exit fullscreen mode

The form handler class might be useful for better reusebility. But here, it only contains one user and one function, so it could easyly substituted by a function, leaving the user as a global definition (which now is encapsulated by the form handler). So, in fact, the user class is the only useful class here.

Pleas don´t misunderstand me, your examples are great as a demonstation. But it also demonstrates a typical misunderstanding: Classes are no value on it´s own. They are only a tool.

By the way: There is no reason not to use functional approaches inside of class functions. And possibly you could write better procedural code, if you try to minimize side effects.

So, from my point of view there are many developers out there, that think they have found the golden calf using one or the other approach. There is nothing like the miracle paradigm that solves all your problems. You will benefit most if you learn to use any approach where it is best suited. If you want to print "Hello world", you even do not need a computer. Use a typewriter instead.