Primer on Layers: Understanding Layer-Based Architectures

A Primer on Layers: Understanding Layer-Based ArchitecturesWhen we’re just getting started, we can only think about the code, and that if we write it and it works, then we’re good to go.However, that is not entirely true, when writing code there are ma…

A Primer on Layers: Understanding Layer-Based Architectures

When we’re just getting started, we can only think about the code, and that if we write it and it works, then we’re good to go.

However, that is not entirely true, when writing code there are many other aspects to consider other than it running. In particular, things like complexity, ease of maintenance, testability, performance, overall syntax and adherence to the coding standards, and many others.

And all those points affect the way you write and structure your code. With that in mind, it would make a lot more sense to consider them before you start putting your hands on the keyboard, that way you only write your code once.

Out of all those factors, in this article, I want to cover what layer-based architectures are, and how they can affect your project’s structure.

What are layers?

The concept of a layer is used in Software Development to separate different concerns or levels of abstraction. You start by thinking at a really high level about the type of tasks your application is going to be performing, and then you create “groups” or “layers” for them.

For instance, consider your classical To-Do app created using HTML, CSS and JavaScript. What type of actions will your app do?

Remember, this is high-level, so we can say:

  1. It’ll let the user interact with the To-Do items through a UI.
  2. It’ll save those items to some type of storage so it can retrieve them in the future.
  3. It’ll validate that we don’t create repeated items and it’ll let us manage their state.

So we have 3 groups or layers:

  1. UI layer, where the presentation takes place
  2. A storage layer where the persistence of the data takes place
  3. And a business logic layer, where we include all the validations and state management code.

As you can see layers are nothing more than a logical group that allows you to organize your logic. At least at this stage, let’s keep going.

How do layers affect your project?

The effect layers can have highly depend on the type of project you are building.

If you’re working on a monorepo-type project, or even something as simple as a monolithic app, the layers will most likely become different folders within the same project.

You could have something like this:

root folder/
|_ src
|_ UI
|_ components
|_ css
|_ core_logic
|_ libs
|_ state_manager.js
|_ index.js
|_ storage
|_ storage.js
|_ db_conn.js
|_ storage_constants.js
|_ public
|_ index.html

Granted, this is just an example of a fake Node.js project, however, you can see how we’re using the layers to organize our code. Could you possibly have all these files and concepts inside a single “src” folder? Absolutely, but the question here isn’t if you can, it’s if you should.

This (or any similar) separation allows you to work on each layer’s code without significantly affecting the other layers. This is the main benefit of this approach.

On the other hand, if instead you have a project split into multiple microservices, you might not need to have the exact same folder structure. Instead, if each layer is small enough you could turn each one into a single project. Or if they are complex, try to split each microservice internally like you would a monolith.

The point is that through the logical separation of responsibilities and concerns you add layers of abstraction that provide you with the tools to better maintain and extend the code.

Classic uses of layers in software architecture

This separation of concerns and its subsequent effect on the internal (or external) structure of your applications is also known as “Architecture”.

The architecture determines how easy or hard it is to scale, maintain and even deploy your application. And just like with anything in the real world, there is no single answer to all problems, so there is no real single architecture that will solve all your problems.

Even better, there are patterns you can use and reuse after some tweaks that will help you structure your projects in the best way possible.

Classic web application architecture: the MVC pattern

The MVC (or Model, View, Controller) pattern is a classic layer-based architecture that allows you to separate the individual data-related logic (i.e how you interact with the data) from the actual presentation (the view) and the way you communicate both (in other words, the controller).

With an MVC pattern, you usually end up having something like React, Vue or heck, even plain old JavaScript for your View layer, and then an API in the back-end. Each endpoint of this API uses a controller, which centralizes the way you use the models and each model is the way you interact with the storage layer through a higher abstraction level interface.

Put another way:

Each layer can only communicate with the adjacent one, so the view can only communicate with the controller but never directly with the model, and the model can only talk to the controller. The only one that can “talk” both ways is the controller, due to its particular placement.

This is a great basic pattern to tackle any web application because there is a very natural mapping between your app components and the layers.

There are other patterns that you can extrapolate from this one, I’ll leave that to you, the point here is to understand that each layer will give you a different type of abstraction.

Some layer-based patterns are meant for the entire application (like this one), because they deal with the front-end and the back-end as well. But in the cases where the front-end is complex enough, it might also require its own architecture. So you might find yourself using an MVC overall, but an MVVM for the UI for example.

If you liked what you read so far, consider subscribing to my FREE newsletter “The rambling of an old developer” and get regular advice about the IT industry directly in your inbox.

Creating your own pattern

This article is not about memorizing different layer-based patterns, but instead, it’s about trying to understand how they all work and how you can use them to solve your problems.

Once you understand that layers are just abstraction levels that you add between groups that handle different concerns, you can start creating your own patterns and your own architectures.

For example, imagine you’re creating an API from scratch using something like Node.js and you structure your routes handlers (the functions that will be called a request hits the server) like this:

Granted, the above code doesn’t follow any particular framework, and I’m assuming a given external dependency for the Database connection (in the form of the db object. That said, the code there would work, it’s perfectly valid and it will return the list of active users when you hit the /users URL.

However, we can see several improvement areas:

  1. The direct access to the data through the SQL query and directly using the db object is coupling the hander with our storage medium. If next month, for any reason we need to move this to a MongoDB, all our controllers would have to change, and potentially the way they deal with the data as well.
  2. There is no data model for our API, the schema of the response is defined directly in the handler function (as evidenced in the map method). Imagine having 8 to 10 more handlers that deal with users, if in 6 months you have to change the name of one of the fields returned here, you’d have to update all 10 methods. That’s not efficient.
  3. And finally, the response is given by the JSON representation of our array users by our use of the json method. If in the future we need to add extra attributes to our response, such as the time the query took to run, or debug information, we’re going to have to modify this logic.

Every time you write a piece of code that should be considered “production-ready”, you have to think about scalability and resilience to change in the business logic. Of course, changes there will always mean code changes, but it’s a matter of minimizing the number of changes to apply and the places where you have to apply them.

Taking this into account and the improvement points from above, we can say that we could use a storage layer to abstract away the interaction with the data, and a representation layer to centralize the way our data is returned to the client.

Once these concepts are applied, we could end up with a handler like this:

Line 4 abstracts away all the data modeling and data access code, and line 5 abstracts away the representation of our data. That way if changes in the future require us to modify the way we deal with data, we go to the model definition, if we need to change our response, we go to the response handler. And none of our handler functions is affected.

As an added bonus, if you’re part of a big team, maybe you who only work on handlers, don’t even know about the changes required for the models. This is the type of abstractions you should always aim for and the main benefit of layers.

Conclusion

Layers are a powerful tool that should be used at the start of a project, they help dictate the way you structure your code, the way your data flows through your business logic, and how future-proof your app actually is.

Do not let the term scare you or make you think you don’t need it, layers are simple and powerful, there is no real need to not use them.

Are you going to try layers for your next project or do you still have questions about them? Leave your doubts in the comments and let’s connect!

Bonus: Build Great Design Systems and Micro Frontends

Take frontend development to the next level with independent components. Build and collaborate on component-driven apps to easily unlocks Micro Frontends, and to share components.

OSS Tools like Bit offer a great dev experience for building and composing independent components, and build solo or together with your team.

Give it a try →

An independent product component: watch the auto-generated dependency graph

Learn more


Primer on Layers: Understanding Layer-Based Architectures was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.


Print Share Comment Cite Upload Translate
APA
Fernando Doglio | Sciencx (2024-03-28T12:18:19+00:00) » Primer on Layers: Understanding Layer-Based Architectures. Retrieved from https://www.scien.cx/2022/02/22/primer-on-layers-understanding-layer-based-architectures/.
MLA
" » Primer on Layers: Understanding Layer-Based Architectures." Fernando Doglio | Sciencx - Tuesday February 22, 2022, https://www.scien.cx/2022/02/22/primer-on-layers-understanding-layer-based-architectures/
HARVARD
Fernando Doglio | Sciencx Tuesday February 22, 2022 » Primer on Layers: Understanding Layer-Based Architectures., viewed 2024-03-28T12:18:19+00:00,<https://www.scien.cx/2022/02/22/primer-on-layers-understanding-layer-based-architectures/>
VANCOUVER
Fernando Doglio | Sciencx - » Primer on Layers: Understanding Layer-Based Architectures. [Internet]. [Accessed 2024-03-28T12:18:19+00:00]. Available from: https://www.scien.cx/2022/02/22/primer-on-layers-understanding-layer-based-architectures/
CHICAGO
" » Primer on Layers: Understanding Layer-Based Architectures." Fernando Doglio | Sciencx - Accessed 2024-03-28T12:18:19+00:00. https://www.scien.cx/2022/02/22/primer-on-layers-understanding-layer-based-architectures/
IEEE
" » Primer on Layers: Understanding Layer-Based Architectures." Fernando Doglio | Sciencx [Online]. Available: https://www.scien.cx/2022/02/22/primer-on-layers-understanding-layer-based-architectures/. [Accessed: 2024-03-28T12:18:19+00:00]
rf:citation
» Primer on Layers: Understanding Layer-Based Architectures | Fernando Doglio | Sciencx | https://www.scien.cx/2022/02/22/primer-on-layers-understanding-layer-based-architectures/ | 2024-03-28T12:18:19+00:00
https://github.com/addpipe/simple-recorderjs-demo