Loose Coupling – Frontend Coding Tips

Posted by

Loose coupling is a coding practice to keep modules separate. What it means to the context of frontend development is that HTML, CSS, and JavaScript should not be embedded in one another. Or components should not be created in a way that they depend on other components. Loose coupling helps code maintenance easy for two reasons.

  1. Changes in one area of the code will be less likely to break other parts.
  2. It reduces debugging cost by limiting the area of code that developers should inspect.

Bad Practices – Tight Coupling

I will introduce bad practices to explain why tight coupling is bad first.

JS embedded in HTML Tag

<a onclick="doSomething()">Click me</a>

Changing the function name requires changes to both HTML and JS files. So, it should be written like this.

<!-- HTML -->
<a id="action-btn">Click me</a>
//JS
let actionBtn = document.getElementById("action-btn");
actionBtn.addEventListener("click", doSomething);

CSS embedded in JS

element.style.color = "red";

All styles should be defined in CSS file so that developers do not have to look in both JS and CSS files. So, the solution is to define the CSS class and add it to the element’s classList object.

element.classList.add("text-danger");

HTML embedded in JS

element.innerHTML = `<p>Hello, ${userName}!</p>`;

This can cause confusion because the HTML file is missing that part. Allowing this requires developers to look at both JavaScript and HTML files to identify where that part comes from. In order to keep it simple, there are two solutions.

  1. Load from server
  2. Client-side template

These solutions require either extra HTTP request or template engine. For the first solution, you will make a request for the lines of HTML from the server and inject them into a specified HTML tags. That way, those lines of code can be maintained in a HTML file for the specific request. For the second solution, the template engine can generate these lines of HTML dynamically so that it will stay in the same HTML file.

<!-- solution #2 -->
<div>
    <p>Hello, {{userName}}</p>
</div>

Conclusion

Loose coupling will help code maintenance easy by reducing dependency among components and limiting the area of code to inspect. This practice is especially recommended for a large application or team development. Avoid these bad practices and keep codebase clean so that developers won’t have hard time implementing changes and debugging!

Thanks for reading.

Hope you enjoyed the article. If you have any question or opinion to share, feel free to write some comments.

Facebook Comments