DEV Community

Santiago Salazar Pavajeau
Santiago Salazar Pavajeau

Posted on

Separation of concerns in JS (cleaner code) Part 1

A fundamental step in the journey to software engineering is to make applications with proper structure. Here, I try to mention some fundamental methods to structure JavaScript code for when apps grow and get more complex.

This example uses vanilla JS, so the dependencies are set simply through <script> tags. So unlike frameworks like React or Angular the separation of concerns has to be built from scratch. Dealing with plain JavaScript really gives insight into why frameworks are so effective.

So initially I used a class-based approach to have some modularity and used an Adapter to encapsulate most of the logic (data and presentational). Then also created classes for the models to set their attributes.

Adapter Code

This was an initial step, but it was not taking functionality into account. So eventually the Adapter became cluttered with many methods with unrelated functionalities that had the potential to be categorized.

In Javascript, some of the main functionalities include API requests, event handling, and DOM manipulation. The way specific types of functions can be organized is through making files that will only contain one category of functionality.

In an initial step to decluttering the Adapter class I divided the methods into three files:

  • apiHelper.js: methods with server-side requests.

  • domEventHelper.js: methods with event handling and DOM manipulation.

  • stateHelper.js: global variables needed throughout the application.

Link to repository

In the next blog, I further break down the domEventHelper.js into a file/module with only DOM manipulation and another only with event handling.

Feel free to reach out with any ideas/thoughts through LinkedIn or Twitter.

Top comments (0)