• Engineering Mathematics
  • Discrete Mathematics
  • Operating System
  • Computer Networks
  • Digital Logic and Design
  • C Programming
  • Data Structures
  • Theory of Computation
  • Compiler Design
  • Computer Org and Architecture

Presentation Layer in OSI model

Prerequisite : OSI Model

Introduction : Presentation Layer is the 6th layer in the Open System Interconnection (OSI) model. This layer is also known as Translation layer, as this layer serves as a data translator for the network. The data which this layer receives from the Application Layer is extracted and manipulated here as per the required format to transmit over the network. The main responsibility of this layer is to provide or define the data format and encryption. The presentation layer is also called as Syntax layer since it is responsible for maintaining the proper syntax of the data which it either receives or transmits to other layer(s).

Functions of Presentation Layer :

The presentation layer, being the 6th layer in the OSI model, performs several types of functions, which are described below-

  • Presentation layer format and encrypts data to be sent across the network.
  • This layer takes care that the data is sent in such a way that the receiver will understand the information (data) and will be able to use the data efficiently and effectively.
  • This layer manages the abstract data structures and allows high-level data structures (example- banking records), which are to be defined or exchanged.
  • This layer carries out the encryption at the transmitter and decryption at the receiver.
  • This layer carries out data compression to reduce the bandwidth of the data to be transmitted (the primary goal of data compression is to reduce the number of bits which is to be transmitted).
  • This layer is responsible for interoperability (ability of computers to exchange and make use of information) between encoding methods as different computers use different encoding methods.
  • This layer basically deals with the presentation part of the data.
  • Presentation layer, carries out the data compression (number of bits reduction while transmission), which in return improves the data throughput.
  • This layer also deals with the issues of string representation.
  • The presentation layer is also responsible for integrating all the formats into a standardized format for efficient and effective communication.
  • This layer encodes the message from the user-dependent format to the common format and vice-versa for communication between dissimilar systems.
  • This layer deals with the syntax and semantics of the messages.
  • This layer also ensures that the messages which are to be presented to the upper as well as the lower layer should be standardized as well as in an accurate format too.
  • Presentation layer is also responsible for translation, formatting, and delivery of information for processing or display.
  • This layer also performs serialization (process of translating a data structure or an object into a format that can be stored or transmitted easily).

Features of Presentation Layer in the OSI model: Presentation layer, being the 6th layer in the OSI model, plays a vital role while communication is taking place between two devices in a network.

List of features which are provided by the presentation layer are:

  • Presentation layer could apply certain sophisticated compression techniques, so fewer bytes of data are required to represent the information when it is sent over the network.
  • If two or more devices are communicating over an encrypted connection, then this presentation layer is responsible for adding encryption on the sender’s end as well as the decoding the encryption on the receiver’s end so that it can represent the application layer with unencrypted, readable data.
  • This layer formats and encrypts data to be sent over a network, providing freedom from compatibility problems.
  • This presentation layer also negotiates the Transfer Syntax.
  • This presentation layer is also responsible for compressing data it receives from the application layer before delivering it to the session layer (which is the 5th layer in the OSI model) and thus improves the speed as well as the efficiency of communication by minimizing the amount of the data to be transferred.

Working of Presentation Layer in the OSI model : Presentation layer in the OSI model, as a translator, converts the data sent by the application layer of the transmitting node into an acceptable and compatible data format based on the applicable network protocol and architecture.  Upon arrival at the receiving computer, the presentation layer translates data into an acceptable format usable by the application layer. Basically, in other words, this layer takes care of any issues occurring when transmitted data must be viewed in a format different from the original format. Being the functional part of the OSI mode, the presentation layer performs a multitude (large number of) data conversion algorithms and character translation functions. Mainly, this layer is responsible for managing two network characteristics: protocol (set of rules) and architecture.

Presentation Layer Protocols : Presentation layer being the 6th layer, but the most important layer in the OSI model performs several types of functionalities, which makes sure that data which is being transferred or received should be accurate or clear to all the devices which are there in a closed network. Presentation Layer, for performing translations or other specified functions, needs to use certain protocols which are defined below –

  • Apple Filing Protocol (AFP): Apple Filing Protocol is the proprietary network protocol (communications protocol) that offers services to macOS or the classic macOS. This is basically the network file control protocol specifically designed for Mac-based platforms.
  • Lightweight Presentation Protocol (LPP): Lightweight Presentation Protocol is that protocol which is used to provide ISO presentation services on the top of TCP/IP based protocol stacks.
  • NetWare Core Protocol (NCP): NetWare Core Protocol is the network protocol which is used to access file, print, directory, clock synchronization, messaging, remote command execution and other network service functions.
  • Network Data Representation (NDR): Network Data Representation is basically the implementation of the presentation layer in the OSI model, which provides or defines various primitive data types, constructed data types and also several types of data representations.
  • External Data Representation (XDR): External Data Representation (XDR) is the standard for the description and encoding of data. It is useful for transferring data between computer architectures and has been used to communicate data between very diverse machines. Converting from local representation to XDR is called encoding, whereas converting XDR into local representation is called decoding.
  • Secure Socket Layer (SSL): The Secure Socket Layer protocol provides security to the data that is being transferred between the web browser and the server. SSL encrypts the link between a web server and a browser, which ensures that all data passed between them remains private and free from attacks.

author

Please Login to comment...

Similar reads.

  • How to Get a Free SSL Certificate
  • Best SSL Certificates Provider in India
  • Elon Musk's xAI releases Grok-2 AI assistant
  • What is OpenAI SearchGPT? How it works and How to Get it?
  • Content Improvement League 2024: From Good To A Great Article

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

data use cases

Web Application Architecture: How the Web Works

  • Engineering
  • Published: 25 Jul, 2019
  • No comments Share

When building a web application, there are three main principles to bear in mind. From a customer’s point of view, the application should be simple, aesthetically pleasing, and address most of their problems. From the business aspect, a web application should stay aligned with its product/market fit . From a software engineer’s perspective, a web application should be scalable, functional, and able to withstand high traffic loads. All these issues are addressed in the web application’s architecture. We’ll cover the basic concepts of any modern web application and explain how the architecture patterns may differ depending on the application you’re building.

What is Web Application Architecture?

So, what is a web application, and how is it different from a website? The basic definition of a web application is a program that runs on a browser. It’s not a website, but the line between the two is fuzzy. To differentiate a web application from a website, remember these three formal characteristics. A web application:

  • addresses a particular problem, even if it’s simply finding some information
  • is as interactive as a desktop application
  • has a Content Management System

A website is traditionally understood to simply be a combination of static pages. But today, most websites consist of both static and dynamic pages, which makes almost all modern websites - you guessed it! - web applications. In this article, we will use the terms interchangeably. Your computer, or smartphone, or any other device you’re browsing with is called a client. The other half of the web equation is called a server because it serves you the data you request. Their communication is called a client-server model, whose main concern is receiving your request and delivering the response back. Web application architecture is a mechanism that determines how application components communicate with each other. Or, in other words, the way the client and the server are connected is established by web application architecture. Web applications of different sizes and complexity levels all follow the same architectural principle, but details may differ. We will further explain how a basic request-response process works and what components comprise the architecture.

How does the web request work?

web request-response cycle

Web request-response cycle

Let’s look at Amazon.com to illustrate our explanation. First, you visit amazon.com . You type in the URL and as you hit Enter, your browser prepares to recognize this URL, because it needs to know the address of the server where the page is located. So it sends your request to the Domain Name Center (DNS), a repository of domain names and their IP addresses. If you've already visited Amazon from the same browser, it will pull the address from the cache. Then, a browser sends the request to the found IP address using the HTTPS protocol. Second, the web server processes the request . The web server where Amazon.com is located catches the request and sends it to the storage area to locate the page and all data that follows with it. But its route is held via Business Logic (also called Domain Logic and Application Logic). BL manages how each piece of data is accessed and determines this workflow specifically for each application . As BL processes the request, it sends it to storage to locate the looked-for data. Third, you receive your data . Your response travels back to you and you see the content of the web page on your display. The graphical interface you see when scrolling Amazon's or any other website is called the front end of an application - it depicts all UX and UI components so that a user can access the information they came looking for.

Web application architecture components and Three-Tier Architecture

web application architecture

Web application architecture following the three-tier pattern

Presentation layer

The presentation layer is accessible to users via a browser and consists of user interface components and UI process components that support interaction with the system. It’s developed using three core technologies: HTML, CSS, and JavaScript. While HTML is the code that determines what your website will contain, CSS controls how it will look. JavaScript and its frameworks make your website interactive - responsive to a user’s actions. Developers use JavaScript frameworks such as Angular and React to make the content on the page dynamic.

Business layer

This layer, also called Business Logic or Domain Logic or Application Layer, accepts user requests from the browser, processes them, and determines the routes through which the data will be accessed. The workflows by which the data and requests travel through the back end are encoded in a business layer. For example, if your application is a hotel booking website, business logic will be responsible for the sequence of events a traveler will go through when booking a room. Although business rules can be a manifestation of the business logic, they are not the same. Sometimes business rules are extracted and managed separately, using a Business Rules Management System, as we discussed in our article on back office systems .

Persistence layer

Also called the storage or data access layer, the persistance layer is a centralized location that receives all data calls and provides access to the persistent storage of an application. The persistence layer is closely connected to the business layer, so the logic knows which database to talk to and the data retrieving process is more optimized. The data storage infrastructure includes a server and a Database Management System , software to communicate with the database itself, applications, and user interfaces to obtain data and parse it. Typically you can store your data either in owned hardware servers or in the cloud - meaning, that you purchase data center management and maintenance services while accessing your storage virtually. Using the services of cloud technology providers such as Amazon, Google, or Microsoft, you can utilize Infrastructure-as-a-Service, Platform-as-a-Service, or serverless approaches to cloud management. There are also components that usually exist in all web applications but are separated from the main layers: Cross-cutting code. This component handles other application concerns such as communications, operational management, and security. It affects all parts of the system but should never mix with them. Third-party integrations . Payment gateways, social logins, GDSs in travel websites are all integrations connected to the application’s back end via pieces of code called APIs. They allow your software to source data from other software and widen your functionality without coding it from scratch. Read how APIs work in our dedicated article. Let’s see how the three-tier architecture is implemented in different types of web applications.

Example #1. Dynamic web pages, SPAs, and MPAs

The application’s front end can serve either static or dynamic content. In most cases, it’s a combination of both. Static Web Pages exist on a server as they are and contain information that doesn’t change. Dynamic Web Pages change information every day or in response to a user’s request - think of any news website or your Twitter feed. The combination of dynamic and static content makes up a web application. The simplest example of a web application with dynamic content is a Single Page Application.

Single Page Applications

SPA architecture

Single Page Application architecture

When the role of the server is reduced to data services, this is sometimes called thin server architecture. We can’t talk about SPAs without mentioning the more traditional model - Multi-Page Applications.

Multi-Page Applications

multi-page applications

MPA architecture

As opposed to the SPA’s client-side scripting, traditional applications are written using both client- and server-side languages. Server-side scripting means that all operations are performed on the server’s end, so when you request content, it processes the script, retrieves data from the storage and chooses the content to display. Server-scripting languages you should be familiar with include PHP, Java , Python, Ruby, C#, and more.

Example #2. Enterprise applications

enterprise application architecture

Enterprise application architecture

Apart from an extra layer, enterprise applications have access to data sources from other applications in an organization, making it a network of software solutions, connected by APIs. Besides, there are more groups of users who have access to different functional components - they can be business partners, clients, admins, and several groups of staff. Sometimes the presentation tiers are separate for all of them, so you can deploy the application as intranet or extranet.

To conclude

This, hopefully, sheds some light on the backstage of building modern websites. In this article, we dipped our toes into the complicated subject of software engineering. If this wasn’t enough for you, feel free to roam around our blog a bit more and specifically explore the following articles. The Good and the Bad of JavaScript Full Stack Development Technical Documentation in Software Development: Types, Best Practices, and Tools How to Use Open Source Software: Features, Main Software Types, and Selection Advice

NDepend Blog

Improve your .NET code quality with NDepend

Software_architecture_5_patterns_you_need_to_know

Software Architecture: The 5 Patterns You Need to Know

Share this:.

When I was attending night school to become a programmer, I learned several design patterns : singleton, repository, factory, builder, decorator, etc. Design patterns give us a proven solution to existing and recurring problems. What I didn’t learn was that a similar mechanism exists on a higher level in the form of the software architecture pattern .

These are patterns for the overall layout of your application or applications. They all have advantages and disadvantages. And they all address specific issues.

In this post, we’ll take a look at 5 such patterns in detail.  For each software architecture pattern, this will include a description, its advantages, its disadvantages, and the situation for which it is ideal.  The patterns are as follows.

  • The Layered Architectural Pattern
  • The Microkernel Architectural Pattern
  • The CQRS Architectural Pattern
  • The Event Sourcing Architectural Pattern
  • The Microservices Architectural Pattern

Download the NDepend trial for free and use dependency graphs to get a feel for what your software architecture really looks like.

1. The Layered Architectural Pattern

The layered pattern is probably one of the most well-known software architecture patterns.

Many developers use it, without really knowing its name. The idea is to split up your code into “layers”, where each layer has a certain responsibility and provides a service to a higher layer.

There isn’t a predefined number of layers, but these are the ones you see most often:

  • Presentation or UI layer
  • Application layer
  • Business or domain layer
  • Persistence or data access layer
  • Database layer

The idea is that the user initiates a piece of code in the presentation layer by performing some action (e.g. clicking a button). The presentation layer then calls the underlying layer, i.e. the application layer.

Then we go into the business layer and finally, the persistence layer stores everything in the database. So higher layers are dependent upon and make calls to the lower layers.

ui presentation layer

You will see variations of this, depending on the complexity of the applications. Some applications might omit the application layer, while others add a caching layer.

It’s even possible to merge two layers into one. For example, the ActiveRecord pattern combines the business and persistence layers.

Layer Responsibility

As mentioned, each layer has its own responsibility.

The presentation layer contains the graphical design of the application, as well as any code to handle user interaction. You shouldn’t add logic that is not specific to the user interface in this layer.

The business layer is where you put the models and logic that is specific to the business problem you are trying to solve.

The application layer sits between the presentation layer and the business layer.

On the one hand, it provides an abstraction so that the presentation layer doesn’t need to know the business layer. In theory, you could change the technology stack of the presentation layer without changing anything else in your application (e.g. change from WinForms to WPF).

On the other hand, the application layer provides a place to put certain coordination logic that doesn’t fit in the business or presentation layer.

ui presentation layer

Finally, the persistence layer contains the code to access the database layer. The database layer is the underlying database technology (e.g. SQL Server, MongoDB). The persistence layer is the set of code to manipulate the database: SQL statements, connection details, etc.

  • Most developers are familiar with this pattern.
  • It provides an easy way of writing a well-organized and testable application .

Disadvantages

  • It tends to lead to monolithic applications that are hard to split up afterward.
  • Developers often find themselves writing a lot of code to pass through the different layers, without adding any value in these layers. If all you are doing is writing a simple CRUD application, the layered pattern might be overkill for you.
  • Standard line-of-business apps that do more than just CRUD operations

2. The Microkernel Architectural Pattern

The microkernel pattern, or plug-in pattern, is useful when your application has a core set of responsibilities and a collection of interchangeable parts on the side. The microkernel will provide the entry point and the general flow of the application, without really knowing what the different plug-ins are doing.

ui presentation layer

An example is a task scheduler.

The microkernel could contain all the logic for scheduling and triggering tasks, while the plug-ins contain specific tasks. As long as the plug-ins adhere to a predefined API, the microkernel can trigger them without needing to know the implementation details.

Another example is a workflow. The implementation of a workflow contains concepts like the order of the different steps, evaluating the results of steps, deciding what the next step is, etc. The specific implementation of the steps is less important to the core code of the workflow.

  • This pattern provides great flexibility and extensibility.
  • Some implementations allow for adding plug-ins while the application is running.
  • Microkernel and plug-ins can be developed by separate teams.
  • It can be difficult to decide what belongs in the microkernel and what doesn’t.
  • The predefined API might not be a good fit for future plug-ins.
  • Applications that take data from different sources, transform that data and writes it to different destinations
  • Workflow applications
  • Task and job scheduling applications

3. The CQRS Architectural Pattern

CQRS is an acronym for Command and Query Responsibility Segregation . The central concept of this pattern is that an application has read operations and write operations that must be totally separated.

This also means that the model used for write operations (commands) will differ from the read models (queries). Furthermore, the data will be stored in different locations. In a relational database, this means there will be tables for the command model and tables for the read model. Some implementations even store the different models in totally different databases, e.g. SQL Server for the command model and MongoDB for the read model.

This pattern is often combined with event sourcing, which we’ll cover below.

How does it work exactly?

ui presentation layer

When the application needs to show data to the user, it can retrieve the read model by calling the read service, as shown below.

  • Command models can focus on business logic and validation while read models can be tailored to specific scenarios.
  • You can avoid complex queries (e.g. joins in SQL) which makes the reads more performant.
  • Keeping the command and the read models in sync can become complex.
  • Applications that expect a high amount of reads
  • Applications with complex domains

4. The Event Sourcing Architectural Pattern

As I mentioned above, CQRS often goes hand in hand with event sourcing. This is a pattern where you don’t store the current state of your model in the database, but rather the events that happened to the model. So when the name of a customer changes, you won’t store the value in a “Name” column. You will store a “NameChanged” event with the new value (and possibly the old one too).

When you need to retrieve a model, you retrieve all its stored events and reapply them on a new object. We call this rehydrating an object.

A real-life analogy of event sourcing is accounting. When you add an expense, you don’t change the value of the total. In accounting, a new line is added with the operation to be performed.

If an error was made, you simply add a new line. To make your life easier, you could calculate the total every time you add a line. This total can be regarded as the read model. The example below should make it more clear.

ui presentation layer

You can see that we made an error when adding Invoice 201805. Instead of changing the line, we added two new lines: first, one to cancel the wrong line, then a new and correct line.

This is how event sourcing works. You never remove events, because they have undeniably happened in the past. To correct situations, we add new events.

Also, note how we have a cell with the total value. This is simply a sum of all values in the cells above. In Excel, it automatically updates so you could say it synchronizes with the other cells. It is the read model, providing an easy view for the user.

Event sourcing is often combined with CQRS because rehydrating an object can have a performance impact, especially when there are a lot of events for the instance. A fast read model can significantly improve the response time of the application.

  • This software architecture pattern can provide an audit log out of the box. Each event represents a manipulation of the data at a certain point in time.
  • It requires some discipline because you can’t just fix wrong data with a simple edit in the database.
  • It’s not a trivial task to change the structure of an event. For example, if you add a property, the database still contains events without that data. Your code will need to handle this missing data graciously.

Ideal for Applications That:

  •  Need to publish events to external systems
  • Will be built with CQRS
  • Have complex domains
  • Need an audit log of changes to the data

5. The Microservices Architectural Pattern

When you write your application as a set of microservices, you’re actually writing multiple applications that will work together. Each microservice has its own distinct responsibility and teams can develop them independently of other microservices.

The only dependency between them is the communication. As microservices communicate with each other, you will have to make sure messages sent between them remain backwards compatible. This requires some coordination, especially when different teams are responsible for different microservices.

A diagram can explain.

ui presentation layer

You can imagine this is an application where the user can order something. The separate microservices can call each other too. For example, the payment service may notify the orders service when a payment succeeds. The orders service could then call the inventory service to adjust the stock.

There is no clear rule of how big a microservice can be. In the previous example, the user profile service may be responsible for data like the username and password of a user, but also the home address, avatar image, favorites, etc. It could also be an option to split all those responsibilities into even smaller microservices.

  • You can write, maintain, and deploy each microservice separately.
  • A microservices architecture should be easier to scale, as you can scale only the microservices that need to be scaled. There’s no need to scale the less frequently used pieces of the application.
  • It’s easier to rewrite pieces of the application because they’re smaller and less coupled to other parts.
  • Contrary to what you might expect, it’s actually easier to write a well-structured monolith at first and split it up into microservices later. With microservices, a lot of extra concerns come into play: communication, coordination, backward compatibility, logging, etc. Teams that miss the necessary skill to write a well-structured monolith will probably have a hard time writing a good set of microservices.
  • A single action of a user can pass through multiple microservices. There are more points of failure, and when something does go wrong, it can take more time to pinpoint the problem.
  • Applications where certain parts will be used intensively and need to be scaled
  • Services that provide functionality to several other applications
  • Applications that would become very complex if combined into one monolith
  • Applications where clear bounded contexts can be defined

I’ve explained several software architecture patterns, as well as their advantages and disadvantages. But there are more patterns than the ones I’ve laid out here. It is also not uncommon to combine several of these patterns.

They aren’t always mutually exclusive. For example, you could have several microservices and have some of them use the layered pattern, while others use CQRS and event sourcing.

The important thing to remember is that there isn’t one solution that works everywhere. When we ask the question of which pattern to use for an application, the age-old answer still applies: “it depends.”

You should weigh in on the pros and cons of a solution and make a well-informed decision.

Make your .NET code beautiful with NDepend

Download the NDepend Trial and gain valuable insights into your .NET code within a few minutes

  • Pingback: Software Architecture: the 5 Patterns You Need to Know – NDepend – Bitbucket Bits

Nice article, Peter! These are great essentials that every developer should know about.

I like the clear structure of the article. What I’m missing is a suggestion on the architecture of the services of a microservice architecture.

could be added in this list the architecture of ports and adapters, the clean architecture or the onion

Simply fantastic with real-time examples

Comments are closed.

DEV Community

DEV Community

Dino Dujmovic

Posted on May 5, 2023 • Updated on May 7, 2023

Angular Architecture - Abstraction layers

digitaldino

Angular Architecture - Organizing modules

Dino dujmovic ・ apr 18 ・ 5 min read.

Now that we have explored how modular design can be achieved in a standalone Angular application, let's take a closer look at how our application operates and functions by examining it through the lens of abstraction layers .

Abstraction Layers

The concept behind this pattern is to divide the application into discrete layers and establish communication protocols between them.

The pattern aims to split the application into three distinct layers, namely:

  • Abstraction Layer
  • Presentation Layer

abstraction layers data flow

Angular Architecture - Core Module

Dino dujmovic ・ apr 28 ・ 2 min read.

The Core Layer is the central implementation hub for the core application logic, including all data manipulation and external communication. This layer also includes essential business logic, such as API calls for data retrieval.

It's main parts are services for making API calls and/or state management which in case of Angular could be NgRx, NgXs, custom implementation using Subjects or other.

  • API Services have sole purpose to facilitate communication with API endpoints and nothing more.

Movie Service

  • State Management Solution serves as a centralized, immutable data store for the application. By incorporating an Abstraction Layer, we can render our components independent of both the State Management Solution and API/Data Services. This approach makes it much easier to migrate to other data management solutions in the future, as we won't need to modify the Presentational Layer (i.e., the Components).

state management

Abstraction layer

The abstraction layer sits between the presentation and the core layer and handles communication between them. Since, the goal is not to inject API and state providers directly in the presentation layer, rather, we can inject the facade service and use it to interact with the core layer.

So abstraction layer:

  • is implemented as Angular providers/services named facades (example: movies.facade.ts)
  • exposes streams of state and interface
  • is used to store and dispatch actions, observable emissions and expose observables and signals for components to use.

Movies facade

Presentation layer

The presentation layer (UI) layer is where all Angular components reside. Its primary responsibility is to present the application's UI and delegate user actions to the core layer through the abstraction layer.

Inside of presentation layer we have:

Smart/container components:

  • can pass data down to dumb components
  • have facade/s and other services injected
  • communicate with core layer through facades
  • react to events from dumb components
  • are usually page components (meaning they are routable but it is not case)

Smart components

Angular Architecture - Page Modules

Dino dujmovic ・ apr 25 ・ 3 min read.

Dumb/presentational components:

  • recieve their data through @Input() and pass events and data through @Output()
  • do not contain any application logic
  • mostly kept in SharedModule or at specific module components folder

Dumb component

Angular Architecture - Shared Module

Dino dujmovic ・ apr 30 ・ 2 min read.

Example

References:

dev-academy.com/angular-architecture

medium.com/@getrohith.sathya

blog.brecht.io/scalable-angular2

Top comments (1)

pic

Templates let you quickly answer FAQs or store snippets for re-use.

hanneslim profile image

  • Joined Aug 4, 2020

In addition I would highly recommend using a Facade pattern: nerd-corner.com/how-to-build-a-pus...

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .

Hide child comments as well

For further actions, you may consider blocking this person and/or reporting abuse

ruthvik_thimmoji_6fde5e61 profile image

Unlocking Efficiency: Essential Web Development Tools for Modern Developers

Ruthvik thimmoji - Aug 8

dkmen profile image

Understanding the JWT

Drimil Mendapara - Aug 8

ananthu_raj_4a3977a27ee3e profile image

5 DevOps Automation Tools You Should Know About

Ananthu Raj - Aug 23

vyan profile image

6 Must-Know JavaScript ES13 Features for Modern Development 🚀

Vishal Yadav - Aug 28

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Presentation Domain Data Layering

26 August 2015

Martin Fowler

team organization

encapsulation

application architecture

web development

One of the most common ways to modularize an information-rich program is to separate it into three broad layers: presentation (UI), domain logic (aka business logic), and data access. So you often see web applications divided into a web layer that knows about handling HTTP requests and rendering HTML, a business logic layer that contains validations and calculations, and a data access layer that sorts out how to manage persistent data in a database or remote services.

On the whole I've found this to be an effective form of modularization for many applications and one that I regularly use and encourage. It's biggest advantage (for me) is that it allows me to reduce the scope of my attention by allowing me to think about the three topics relatively independently. When I'm working on domain logic code I can mostly ignore the UI and treat any interaction with data sources as an abstract set of functions that give me the data I need and update it as I wish. When I'm working on the data access layer I focus on the details of wrangling the data into the form required by my interface. When I'm working on the presentation I can focus on the UI behavior, treating any data to display or update as magically appearing by function calls. By separating these elements I narrow the scope of my thinking in each piece, which makes it easier for me to follow what I need to do.

This narrowing of scope doesn't imply any sequence to programming them - I usually find I need to iterate between the layers. I might build the data and domain layers off my initial understanding of the UX, but when refining the UX I need to change the domain which necessitates a change to the data layer. But even with that kind of cross-layer iteration, I find it easier to focus on one layer at a time as I make changes. It's similar to the switching of thinking modes you get with refactoring's two hats .

Another reason to modularize is to allow me to substitute different implementations of modules. This separation allows me to build multiple presentations on top of the same domain logic without duplicating it. Multiple presentations could be separate pages in a web app, having a web app plus mobile native apps, an API for scripting purposes, or even an old fashioned command line interface. Modularizing the data source allows me to cope gracefully with a change in database technology, or to support services for persistence that may change with little notice. However I have to mention that while I often hear about data access substitution being a driver for separating the data source layer, I rarely hear of someone actually doing it.

Modularity also supports testability, which naturally appeals to me as a big fan of SelfTestingCode . Module boundaries expose seams that are good affordance for testing . UI code is often tricky to test, so it's good to get as much logic as you can into a domain layer which is easily tested without having to do gymnastics to access the program through a UI 1 . Data access is often slow and awkward, so using TestDoubles around the data layer often makes domain logic testing much easier and responsive.

1: A PageObject is also an important tool to help testing around UIs.

While substitutability and testability are certainly benefits of this layering, I must stress that even without either of these reasons I would still divide into layers like this. The reduced scope of attention reason is sufficient on its own.

When talking about this we can either look at it as one pattern (presentation-domain-data) or split it into two patterns (presentation-domain, and domain-data). Both points of view are useful - I think of presentation-domain-data as a composite of presentation-domain and domain-data.

I consider these layers to be a form of module, which is a generic word I use for how we clump our software into relatively independent pieces. Exactly how this corresponds to code depends on the programming environment we're in. Usually the lowest level is some form of subroutine or function. An object-oriented language will have a notion of class that collects functions and data structure. Most languages have some form of higher level called packages or namespaces, which often can be formed into a hierarchy. Modules may correspond to separately deployable units: libraries, or services, but they don't have to.

Layering can occur at any of these levels. A small program may just put separate functions for the layers into different files. A larger system may have layers corresponding to namespaces with many classes in each.

I've mentioned three layers here, but it's common to see architectures with more than three layers. A common variation is to put a service layer between the domain and presentation, or to split the presentation layer into separate layers with something like Presentation Model . I don't find that more layers breaks the essential pattern, since the core separations still remain.

The dependencies generally run from top to bottom through the layer stack: presentation depends on the domain, which then depends on the data source. A common variation is to arrange things so that the domain does not depend on its data sources by introducing a mapper between the domain and data source layers. This approach is often referred to as a Hexagonal Architecture .

These layers are logical layers not physical tiers. I can run all three layers on my laptop, I can run the presentation and domain model in a desktop with a database on a server, I can split the presentation with a rich client in the browser and a Backed For Frontend on the server. In that case I treat the BFF as a presentation layer as it's focused on supporting a particular presentation option.

Although presentation-domain-data separation is a common approach, it should only be applied at a relatively small granularity. As an application grows, each layer can get sufficiently complex on its own that you need to modularize further. When this happens it's usually not best to use presentation-domain-data as the higher level of modules. Often frameworks encourage you to have something like view-model-data as the top level namespaces; that's OK for smaller systems, but once any of these layers gets too big you should split your top level into domain oriented modules which are internally layered.

Developers don't have to be full-stack but teams should be.

One common way I've seen this layering lead organizations astray is the AntiPattern of separating development teams by these layers. This looks appealing because front-end and back-end development require different frameworks (or even languages) making it easy for developers to specialize in one or the other. Putting those people with common skills together supports skill sharing and allows the organization to treat the team as a provider of a single, well-delineated type of work. In the same way, putting all the database specialists together fits in with the common centralization of databases and schemas. But the rich interplay between these layers necessitates frequent swapping between them. This isn't too hard when you have specialists in the same team who can casually collaborate, but team boundaries add considerable friction, as well as reducing an individual's motivation to develop the important cross-layer understanding of a system. Worse, separating the layers into teams adds distance between developers and users. Developers don't have to be full-stack (although that is laudable) but teams should be.

Further Reading

I've written about this separation from a number of different angles elsewhere. This layering drives the structure of P of EAA and chapter 1 of that book talks more about this layering. I didn't make this layering a pattern in its own right in that book but have toyed with that territory with Separated Presentation and PresentationDomainSeparation .

For more on why presentation-domain-data shouldn't be the highest level modules in a larger system, take a look at the writing and speaking of Simon Brown . I also agree with him that software architecture should be embedded in code.

I had a fascinating discussion with my colleague Badri Janakiraman about the nature of hexagonal architectures. The context was mostly around applications using Ruby on Rails, but much of the thinking applies to other cases when you may be considering this approach.

Acknowledgements

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Presentation VS Application layer in DDD

I have trouble drawing a clear line between Presentation and Application layer in Domain Driven Design.

Where should Controllers, Views, Layouts, Javascript and CSS files go?

Is it in the Application or the Presentation layer?

And if they go all together in the same layer, what contains the other one? Is it empty?

  • architecture
  • domain-driven-design

Matthieu Napoli's user avatar

3 Answers 3

Just because someone created and named "Application Layer" and "Presentation Layer" doesn't mean your application should have them. You should create layers AFTER you created substantial amount of code which you grouped together and want to name this group for sake of communication between developers and clarity of code.

From point of DDD. Application Layer is everything that is not Domain layer. Which includes application logic, presentation and application services.

Euphoric's user avatar

  • 3 Thank you, indeed you made me realize that for my case separating Application and Presentation is useless. Simplicity first! –  Matthieu Napoli Commented Dec 24, 2012 at 9:43
  • If DDD has REST API instead of UI in presentation layer, would REST API be an application or presentation layer. I am now confused, since I was sure that REST API is a presentation layer.. –  Dario Granich Commented May 6, 2016 at 13:33
  • 15 Actually, DDD prescribes four layers in the following order, from higher to lower: Presentation, Application, Domain, Infrastructure. So, the Application layer does not include "presentation". Also, it's always a good idea to decide on the layers before a significant amount of code is written, as it isn't only about grouping code together but also about constraining the direction of compile-time dependencies. –  Rogério Commented Feb 21, 2017 at 17:36

There is a big difference between the application layer and the presentation layer from a DDD view point.

Although DDD centers around how to model the domain using the DDD building blocks and concepts such as bounded contexts, Ubiquitous language and so, it is still vital to clearly identify and separate the various layers in your app.

The architecture plays a big role in implementing a successful DDD app. A famous architecture that gained a lot of hype lately is the onion architecture:

enter image description here

In this design the UI/Presentation layer and the application layer are clearly separated. Merging the 2 together introduces tight coupling between 2 layers that have clear separate concerns and responsibilities.

The Presentation layer should only house presentation logic. Avoid Smart UIs that know too much. This mainly houses the MVC's Controllers and views in addition to CSS, JS, templates, forms and everything that relates to response and request objects.

The actions issued through presentation are delegated to the application layer through commands. The application layer contains the application logic. It normally maps to a use case. It contains WHAT the system should do to satisfy a use case. A typical application service will ask a repository to return an aggregate then invoke an action on that aggregate.

Have a look at the sample project from Vaughn Vernon's IDDD

Songo's user avatar

  • 2 +1. This is how i've implemented my project. Immediately, i was able to make gains by doing so. Since I abstracted to an application layer, I was able to have multiple presentation layers. For example, our web api and our web site both consume the application layer which saved a lot of time and duplicated code since my web app doesn't have to frame messaging to and from the web api and it keeps all of the logic in sync between the two. –  Sinaesthetic Commented Jan 21, 2016 at 1:47
  • Where are entry point and composition root placed? I always thought it was a responsibility of Application layer. But now it looks like this is Presentation layer. –  Denis535 Commented Feb 24, 2020 at 22:00

Domain Driven Design has nothing to do with either Presentation layer or Application layer. DDD is a methodology whose main focus is on the Domain layer. That is, DDD does not impose any constraints regarding any other layer except for the Domain layer and Your question as well could be asked in the context of any other methodology.

That being said, it's very common to use a four-layer architecture for DDD applications. Here's an example of one such application showing the layers and their intended use: DDDSample Architecture . So, if you choose to use this architecture your views and layouts would go to the Interfaces layer and the controllers, if interface-independent, would go to the Application layer.

You might as well choose any other kind of architecture, as I've said DDD does not impose constraints. There are many MVC frameworks out there that have different structures and yet could also be used for DDD applications. Then, of course, you would place Your views and layouts accordingly.

gnat's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Software Engineering Stack Exchange. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged architecture domain-driven-design layers or ask your own question .

  • The Overflow Blog
  • Where does Postgres fit in a world of GenAI and vector databases?
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites

Hot Network Questions

  • How would you say a couple of letters (as in mail) if they're not necessarily letters?
  • Too many \setmathfont leads to "Too many symbol fonts declared" error
  • Searching for an illustrated children's book with anthropomorphic animals, a sled, and a train
  • Why does flow separation cause an increase in pressure drag?
  • Has a tire ever exploded inside the Wheel Well?
  • Passport Carry in Taiwan
  • Is this a new result about hexagon?
  • Has the US said why electing judges is bad in Mexico but good in the US?
  • How could I contact the Betriebsrat (Workers' Union) of my employer behind his back?
  • How did Oswald Mosley escape treason charges?
  • Command-line script that strips out all comments in given source files
  • What is the name of this simulator
  • How do eradicated diseases make a comeback?
  • Correct Expression for Centripetal Force
  • Two way ANOVA or two way repeat measurement ANOVA
  • DATEDIFF Rounding
  • How much missing data is too much (part 2)? statistical power, effective sample size
  • How does the summoned monster know who is my enemy?
  • Book or novel about an intelligent monolith from space that crashes into a mountain
  • How do enable tagging in a `\list` based environment in `expl3`?
  • Distinctive form of "לאהוב ל-" instead of "לאהוב את"
  • I'm trying to remember a novel about an asteroid threatening to destroy the earth. I remember seeing the phrase "SHIVA IS COMING" on the cover
  • Why was this lighting fixture smoking? What do I do about it?
  • Which programming language/environment pioneered row-major array order?

ui presentation layer

Moments Log

Blogging every moment of your life

Breaking Down the Layers: Understanding the Four-tier Software Architecture

Breaking Down the Layers: Understanding the Four-tier Software Architecture

Table of Contents

Introduction to four-tier software architecture, benefits and advantages of four-tier software architecture, key components and layers in four-tier software architecture, best practices for implementing four-tier software architecture.

Unveiling the Essence: Decoding Four-tier Software Architecture

Software architecture is a crucial aspect of any software development project. It provides a blueprint for designing and organizing the various components of a software system. One popular approach to software architecture is the four-tier architecture, which divides the system into four distinct layers . In this article, we will delve into the world of four-tier software architecture, exploring its components and benefits.

At its core, four-tier software architecture is a client-server model that separates the user interface, business logic, data storage, and data access layers. Each layer has a specific role and interacts with the other layers in a well-defined manner. This separation of concerns allows for better scalability, maintainability, and flexibility in software development.

The first layer of the four-tier architecture is the presentation layer, also known as the user interface layer. This layer is responsible for presenting information to the user and receiving user input. It includes components such as web pages, forms, and graphical user interfaces. The presentation layer communicates with the business logic layer to retrieve and display data to the user.

Moving down the architecture, we come to the business logic layer. This layer contains the core functionality of the software system. It processes user requests, performs calculations, and enforces business rules. The business logic layer acts as the intermediary between the presentation layer and the data access layer, ensuring that data is retrieved and manipulated correctly.

Next, we have the data access layer. This layer is responsible for interacting with the database or any other data storage mechanism. It handles tasks such as retrieving, updating, and deleting data. The data access layer abstracts the underlying data storage technology, allowing the other layers to work with data in a consistent manner. It provides a level of separation between the business logic layer and the data storage layer, making it easier to switch databases or make changes to the data storage mechanism.

Finally, we reach the data storage layer, which is where the actual data is stored. This layer can consist of a relational database, a file system, or any other data storage technology. The data storage layer is responsible for ensuring data integrity, security, and availability. It is accessed by the data access layer to retrieve and store data.

Now that we have a basic understanding of the four-tier software architecture, let’s explore its benefits. One of the main advantages of this architecture is its modularity. Each layer can be developed and maintained independently, allowing for easier testing, debugging, and updates. Changes made to one layer do not necessarily affect the other layers, reducing the risk of unintended consequences.

Another benefit is scalability. The four-tier architecture allows for horizontal scaling, meaning that additional servers can be added to handle increased user load. This scalability is achieved by distributing the workload across multiple servers, with each server responsible for a specific layer. This distributed approach improves performance and ensures that the system can handle a growing number of users.

Additionally, the four-tier architecture promotes reusability. By separating the different layers, developers can reuse components across multiple projects. For example, the business logic layer can be reused in different user interfaces or with different data storage mechanisms. This reusability saves time and effort in software development, leading to faster delivery and reduced costs.

In conclusion, the four-tier software architecture provides a structured approach to software development, dividing the system into four distinct layers. Each layer has a specific role and interacts with the other layers in a well-defined manner. This architecture offers benefits such as modularity, scalability, and reusability. By understanding and implementing the four-tier architecture, software developers can create robust and flexible systems that meet the needs of their users.

Breaking Down the Layers: Understanding the Four-tier Software Architecture

One of the key advantages of four-tier software architecture is its ability to enhance scalability and flexibility. By separating the software into different layers, it becomes easier to modify or replace one layer without affecting the others. This modular approach allows for more efficient development and maintenance, as changes can be made to specific layers without disrupting the entire system. This flexibility is particularly valuable in large-scale software projects where multiple teams are working simultaneously on different components.

Another benefit of four-tier software architecture is improved performance and efficiency. By distributing the workload across multiple layers, the system can handle a higher volume of requests and process them more quickly. For example, the presentation layer, which is responsible for user interaction, can focus solely on rendering the user interface and handling user input, while the business logic layer handles the processing and manipulation of data. This division of labor ensures that each layer can perform its tasks efficiently, resulting in a more responsive and performant software system.

Furthermore, four-tier software architecture promotes reusability and maintainability. With clear separation between layers, developers can reuse components across different projects or even within the same project. This not only saves time and effort but also improves the overall quality of the software. Additionally, the modular nature of this architecture makes it easier to test and debug individual layers, simplifying the maintenance and troubleshooting process. This reduces the risk of introducing new bugs or issues when making changes to the software.

Security is another area where four-tier software architecture excels. By isolating sensitive data and logic in separate layers, it becomes easier to implement security measures at each level. For example, the data layer can enforce strict access controls and encryption mechanisms to protect the integrity and confidentiality of the data. Similarly, the business logic layer can implement authentication and authorization mechanisms to ensure that only authorized users can access certain functionalities. This layered approach to security minimizes the risk of unauthorized access or data breaches, making the software more robust and secure.

Lastly, four-tier software architecture promotes collaboration and teamwork. With clear boundaries between layers, different teams or individuals can work independently on their assigned layers, without stepping on each other’s toes. This promotes parallel development and allows for more efficient collaboration, as teams can focus on their specific areas of expertise. Moreover, the modular nature of this architecture facilitates integration with external systems or third-party components, enabling seamless collaboration with external stakeholders.

In conclusion, four-tier software architecture offers numerous benefits and advantages that make it a popular choice in the development of complex software systems. From enhanced scalability and flexibility to improved performance and efficiency, this architecture promotes reusability, maintainability, security, and collaboration. By understanding and leveraging the advantages of four-tier software architecture, developers can build robust, scalable, and maintainable software systems that meet the evolving needs of businesses and users alike.

In the world of software development, architects and developers often rely on different architectural patterns to design and build robust and scalable applications. One such pattern is the four-tier software architecture, which provides a structured approach to organizing the various components of a software system. Understanding the key components and layers in this architecture is crucial for developers looking to build efficient and maintainable applications.

At its core, the four-tier software architecture consists of four distinct layers: the presentation layer, the application layer, the business logic layer, and the data layer. Each layer has its own set of responsibilities and interacts with the layers above and below it in a well-defined manner.

The presentation layer, also known as the user interface layer, is the layer that users directly interact with. It is responsible for presenting information to the user and capturing user input. This layer typically includes components such as web pages, mobile app screens, and user input forms. Its primary goal is to provide a user-friendly interface that allows users to interact with the application easily.

Moving down the stack, we come to the application layer. This layer acts as a bridge between the presentation layer and the business logic layer. It handles user requests, processes them, and coordinates the flow of data between the presentation layer and the business logic layer. In simpler terms, it acts as a mediator, ensuring that the user’s actions are translated into meaningful operations that the business logic layer can understand.

The business logic layer, also known as the application layer, is where the core functionality of the software resides. It contains the business rules, algorithms, and workflows that define how the application operates. This layer is responsible for processing data, performing calculations, and enforcing business rules. It acts as the brain of the application, making decisions and orchestrating the overall behavior of the system.

Finally, we have the data layer, which is responsible for managing the storage and retrieval of data. This layer interacts with databases, file systems, or any other data storage mechanism used by the application. It handles tasks such as reading and writing data, querying databases, and ensuring data integrity. The data layer plays a critical role in ensuring that the application can store and retrieve data efficiently and reliably.

Understanding the interactions between these layers is crucial for building a well-structured and maintainable software system. Each layer has its own set of responsibilities, and they work together to create a cohesive and efficient application. For example, the presentation layer interacts with the application layer to handle user input and display information to the user. The application layer, in turn, interacts with the business logic layer to process user requests and enforce business rules. Finally, the business logic layer interacts with the data layer to store and retrieve data as needed.

By breaking down the software system into these distinct layers, developers can achieve a high degree of modularity and separation of concerns. Each layer can be developed and tested independently, making it easier to maintain and extend the application over time. Additionally, this architecture allows for scalability, as each layer can be scaled independently based on the specific needs of the application.

In conclusion, the four-tier software architecture provides a structured approach to organizing the components of a software system. Understanding the key components and layers in this architecture is crucial for developers looking to build efficient and maintainable applications. By breaking down the system into the presentation layer, application layer, business logic layer, and data layer, developers can achieve modularity, separation of concerns, and scalability. So, the next time you embark on a software development project, consider leveraging the power of the four-tier software architecture to build robust and scalable applications.

In today’s digital age, software architecture plays a crucial role in the development and implementation of complex applications. One popular approach to software architecture is the four-tier architecture, which provides a structured and scalable framework for building robust software systems. In this article, we will delve into the best practices for implementing four-tier software architecture, breaking down each layer and exploring its purpose and benefits.

The first layer of the four-tier architecture is the presentation layer. This layer is responsible for handling the user interface and interaction with the application. It focuses on providing a seamless and intuitive user experience, ensuring that the application is visually appealing and easy to navigate. By separating the presentation layer from the other layers, developers can make changes to the user interface without affecting the underlying business logic. This layer also enables the use of different presentation technologies, such as web or mobile, depending on the requirements of the application.

Moving on to the second layer, we have the application layer. This layer acts as the bridge between the presentation layer and the business logic layer. It handles the processing of user requests, validates input data, and coordinates the flow of information between the presentation and business logic layers. By encapsulating these responsibilities in a separate layer, developers can ensure that the application remains modular and maintainable. Additionally, the application layer enables the implementation of business rules and logic, making it easier to modify and extend the functionality of the application.

Next, we have the business logic layer, which forms the core of the application. This layer is responsible for implementing the business rules and processes that drive the application’s functionality. It handles complex calculations, data validation, and database operations. By separating the business logic from the other layers, developers can ensure that the application remains flexible and scalable. This layer also promotes code reusability, as the business logic can be shared across multiple applications or modules.

Finally, we have the data access layer, which is responsible for interacting with the underlying data storage systems, such as databases or external APIs. This layer handles the retrieval, storage, and manipulation of data, ensuring that the application has access to the necessary information. By separating the data access logic from the other layers, developers can easily switch between different data sources or make changes to the database schema without affecting the rest of the application. This layer also improves performance by optimizing data retrieval and minimizing network latency.

Implementing four-tier software architecture requires careful planning and adherence to best practices. One important aspect is the separation of concerns, where each layer focuses on a specific set of responsibilities. This separation enables modularity, maintainability, and scalability, making it easier to develop and evolve the application over time. Additionally, developers should strive for loose coupling between the layers, minimizing dependencies and promoting code reusability.

Another best practice is the use of well-defined interfaces between the layers. This allows for easy integration and testing, as each layer can be developed and tested independently. It also promotes interoperability, as different layers can be implemented using different technologies or programming languages. By adhering to these best practices, developers can ensure that the four-tier software architecture is implemented effectively and efficiently.

In conclusion, understanding the four-tier software architecture is essential for building robust and scalable applications. By breaking down each layer and exploring its purpose and benefits, developers can gain a deeper understanding of how the architecture works and how to implement it effectively. By following best practices such as separation of concerns and well-defined interfaces, developers can ensure that their applications are modular, maintainable, and scalable. So, whether you are a seasoned developer or just starting your journey in software architecture, the four-tier architecture is definitely worth exploring.

  • Español – América Latina
  • Português – Brasil
  • Tiếng Việt
  • Android Developers

Guide to app architecture

This guide encompasses best practices and recommended architecture for building robust, high-quality apps.

Mobile app user experiences

A typical Android app contains multiple app components , including activities , fragments , services , content providers , and broadcast receivers . You declare most of these app components in your app manifest . The Android OS then uses this file to decide how to integrate your app into the device's overall user experience. Given that a typical Android app might contain multiple components and that users often interact with multiple apps in a short period of time, apps need to adapt to different kinds of user-driven workflows and tasks.

Keep in mind that mobile devices are also resource-constrained, so at any time, the operating system might kill some app processes to make room for new ones.

Given the conditions of this environment, it's possible for your app components to be launched individually and out-of-order, and the operating system or user can destroy them at any time. Because these events aren't under your control, you shouldn't store or keep in memory any application data or state in your app components, and your app components shouldn't depend on each other.

Common architectural principles

If you shouldn't use app components to store application data and state, how should you design your app instead?

As Android apps grow in size, it's important to define an architecture that allows the app to scale, increases the app's robustness, and makes the app easier to test.

An app architecture defines the boundaries between parts of the app and the responsibilities each part should have. In order to meet the needs mentioned above, you should design your app architecture to follow a few specific principles.

Separation of concerns

The most important principle to follow is separation of concerns . It's a common mistake to write all your code in an Activity or a Fragment . These UI-based classes should only contain logic that handles UI and operating system interactions. By keeping these classes as lean as possible, you can avoid many problems related to the component lifecycle, and improve the testability of these classes.

Keep in mind that you don't own implementations of Activity and Fragment ; rather, these are just glue classes that represent the contract between the Android OS and your app. The OS can destroy them at any time based on user interactions or because of system conditions like low memory. To provide a satisfactory user experience and a more manageable app maintenance experience, it's best to minimize your dependency on them.

Drive UI from data models

Another important principle is that you should drive your UI from data models, preferably persistent models. Data models represent the data of an app. They're independent from the UI elements and other components in your app. This means that they are not tied to the UI and app component lifecycle, but will still be destroyed when the OS decides to remove the app's process from memory.

Persistent models are ideal for the following reasons:

Your users don't lose data if the Android OS destroys your app to free up resources.

Your app continues to work in cases when a network connection is flaky or not available.

If you base your app architecture on data model classes, you make your app more testable and robust.

Single source of truth

When a new data type is defined in your app, you should assign a Single Source of Truth (SSOT) to it. The SSOT is the owner of that data, and only the SSOT can modify or mutate it. To achieve this, the SSOT exposes the data using an immutable type, and to modify the data, the SSOT exposes functions or receive events that other types can call.

This pattern brings multiple benefits:

  • It centralizes all the changes to a particular type of data in one place.
  • It protects the data so that other types cannot tamper with it.
  • It makes changes to the data more traceable. Thus, bugs are easier to spot.

In an offline-first application, the source of truth for application data is typically a database. In some other cases, the source of truth can be a ViewModel or even the UI.

Unidirectional Data Flow

The single source of truth principle is often used in our guides with the Unidirectional Data Flow (UDF) pattern. In UDF, state flows in only one direction. The events that modify the data flow in the opposite direction.

In Android, state or data usually flow from the higher-scoped types of the hierarchy to the lower-scoped ones. Events are usually triggered from the lower-scoped types until they reach the SSOT for the corresponding data type. For example, application data usually flows from data sources to the UI. User events such as button presses flow from the UI to the SSOT where the application data is modified and exposed in an immutable type.

This pattern better guarantees data consistency, is less prone to errors, is easier to debug and brings all the benefits of the SSOT pattern.

Recommended app architecture

This section demonstrates how to structure your app following recommended best practices.

Considering the common architectural principles mentioned in the previous section, each application should have at least two layers:

  • The UI layer that displays application data on the screen.
  • The data layer that contains the business logic of your app and exposes application data.

You can add an additional layer called the domain layer to simplify and reuse the interactions between the UI and data layers.

ui presentation layer

Modern App Architecture

This Modern App Architecture encourages using the following techniques, among others:

  • A reactive and layered architecture.
  • Unidirectional Data Flow (UDF) in all layers of the app.
  • A UI layer with state holders to manage the complexity of the UI.
  • Coroutines and flows.
  • Dependency injection best practices.

For more information, see the following sections, the other Architecture pages in the table of contents, and the recommendations page that contains a summary of the most important best practices.

The role of the UI layer (or presentation layer ) is to display the application data on the screen. Whenever the data changes, either due to user interaction (such as pressing a button) or external input (such as a network response), the UI should update to reflect the changes.

The UI layer is made up of two things:

  • UI elements that render the data on the screen. You build these elements using Views or Jetpack Compose functions.
  • State holders (such as ViewModel classes) that hold data, expose it to the UI, and handle logic.

ui presentation layer

To learn more about this layer, see the UI layer page .

The data layer of an app contains the business logic . The business logic is what gives value to your app—it's made of rules that determine how your app creates, stores, and changes data.

The data layer is made of repositories that each can contain zero to many data sources . You should create a repository class for each different type of data you handle in your app. For example, you might create a MoviesRepository class for data related to movies, or a PaymentsRepository class for data related to payments.

ui presentation layer

Repository classes are responsible for the following tasks:

  • Exposing data to the rest of the app.
  • Centralizing changes to the data.
  • Resolving conflicts between multiple data sources.
  • Abstracting sources of data from the rest of the app.
  • Containing business logic.

Each data source class should have the responsibility of working with only one source of data, which can be a file, a network source, or a local database. Data source classes are the bridge between the application and the system for data operations.

To learn more about this layer, see the data layer page .

Domain layer

The domain layer is an optional layer that sits between the UI and data layers.

The domain layer is responsible for encapsulating complex business logic, or simple business logic that is reused by multiple ViewModels. This layer is optional because not all apps will have these requirements. You should use it only when needed—for example, to handle complexity or favor reusability.

ui presentation layer

Classes in this layer are commonly called use cases or interactors . Each use case should have responsibility over a single functionality. For example, your app could have a GetTimeZoneUseCase class if multiple ViewModels rely on time zones to display the proper message on the screen.

To learn more about this layer, see the domain layer page .

Manage dependencies between components

Classes in your app depend on other classes in order to function properly. You can use either of the following design patterns to gather the dependencies of a particular class:

  • Dependency injection (DI) : Dependency injection allows classes to define their dependencies without constructing them. At runtime, another class is responsible for providing these dependencies.
  • Service locator : The service locator pattern provides a registry where classes can obtain their dependencies instead of constructing them.

These patterns allow you to scale your code because they provide clear patterns for managing dependencies without duplicating code or adding complexity. Furthermore, these patterns allow you to quickly switch between test and production implementations.

We recommend following dependency injection patterns and using the Hilt library in Android apps. Hilt automatically constructs objects by walking the dependency tree, provides compile-time guarantees on dependencies, and creates dependency containers for Android framework classes.

General best practices

Programming is a creative field, and building Android apps isn't an exception. There are many ways to solve a problem; you might communicate data between multiple activities or fragments, retrieve remote data and persist it locally for offline mode, or handle any number of other common scenarios that nontrivial apps encounter.

Although the following recommendations aren't mandatory, in most cases following them makes your code base more robust, testable, and maintainable in the long run:

Don't store data in app components.

Avoid designating your app's entry points—such as activities, services, and broadcast receivers—as sources of data. Instead, they should only coordinate with other components to retrieve the subset of data that is relevant to that entry point. Each app component is rather short-lived, depending on the user's interaction with their device and the overall current health of the system.

Reduce dependencies on Android classes.

Your app components should be the only classes that rely on Android framework SDK APIs such as Context , or Toast . Abstracting other classes in your app away from them helps with testability and reduces coupling within your app.

Create well-defined boundaries of responsibility between various modules in your app.

For example, don't spread the code that loads data from the network across multiple classes or packages in your code base. Similarly, don't define multiple unrelated responsibilities—such as data caching and data binding—in the same class. Following the recommended app architecture will help you with this.

Expose as little as possible from each module.

For example, don't be tempted to create a shortcut that exposes an internal implementation detail from a module. You might gain a bit of time in the short term, but you are then likely to incur technical debt many times over as your codebase evolves.

Focus on the unique core of your app so it stands out from other apps.

Don't reinvent the wheel by writing the same boilerplate code again and again. Instead, focus your time and energy on what makes your app unique, and let the Jetpack libraries and other recommended libraries handle the repetitive boilerplate.

Consider how to make each part of your app testable in isolation.

For example, having a well-defined API for fetching data from the network makes it easier to test the module that persists that data in a local database. If instead, you mix the logic from these two modules in one place, or distribute your networking code across your entire code base, it becomes much more difficult—if not impossible—to test effectively.

Types are responsible for their concurrency policy.

If a type is performing long-running blocking work, it should be responsible for moving that computation to the right thread. That particular type knows the type of computation that it is doing and in which thread it should be executed. Types should be main-safe, meaning they're safe to call from the main thread without blocking it.

Persist as much relevant and fresh data as possible.

That way, users can enjoy your app's functionality even when their device is in offline mode. Remember that not all of your users enjoy constant, high-speed connectivity—and even if they do, they can get bad reception in crowded places.

Benefits of Architecture

Having a good Architecture implemented in your app brings a lot of benefits to the project and engineering teams:

  • It improves the maintainability, quality and robustness of the overall app.
  • It allows the app to scale. More people and more teams can contribute to the same codebase with minimal code conflicts.
  • It helps with onboarding. As Architecture brings consistency to your project, new members of the team can quickly get up to speed and be more efficient in less amount of time.
  • It is easier to test. A good Architecture encourages simpler types which are generally easier to test.
  • Bugs can be investigated methodically with well defined processes.

Investing in Architecture also has a direct impact in your users. They benefit from a more stable application, and more features due to a more productive engineering team. However, Architecture also requires an up-front time investment. To help you justify this time to the rest of your company, take a look at these case studies where other companies share their success stories when having a good architecture in their app.

The following Google samples demonstrate good app architecture. Go explore them to see this guidance in practice:

Recommended for you

  • Note: link text is displayed when JavaScript is off

Content and code samples on this page are subject to the licenses described in the Content License . Java and OpenJDK are trademarks or registered trademarks of Oracle and/or its affiliates.

Last updated 2023-12-12 UTC.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

UI, Business Logic Layer, Data Layer and where to put web services

We are developing a web application. We want to possibly reuse the work we do here for a different application that will use the same database, and use the same business rules for reading and writing to said database.

Which design would be more correct

Having the UI call web services, which would use business objects containing the business logic, which would talk to the data access layer.

Have the UI use business objects containing the business logic, which would call web services, which would then talk to the data access layer.

Have the UI user business objects containing the business logic, which would talk to the data access layer.

  • web-services
  • web-applications
  • data-access-layer
  • business-objects
  • business-logic-layer

7 Answers 7

Don't mix logical design with physical design. Logical design operates over layers and physical design - tiers. Web Service is not a layer. It is simply a tier. In logical design there is standard approach: UI layer-> BL layer -> DAL In physical design all layers can reside within one client-side application connecting local database, or can be distributed over the remote tiers. But for distributed applications usually is added one more layer: Application layer, which hides from BL layer communication over the wire.

Vitaliy Liptchinsky's user avatar

  • 3 I think this is not the answer of the question where to put web services ? –  siamak Commented Jul 9, 2014 at 14:20

I would say the 3rd one. I tend to think of web services as another presentation layer.

Think of it this way: you have a web UI, which calls your business layer code to do things like create a new user (User.Add), find all products that match a given description (Products.FindByDescription), etc.

You can now re-use that same business layer code to build a set of public-facing web services for 3rd parties to make use of. There can be a method which adds a user - that calls your internal User.Add() method, another one to find products, etc..

What you get is a parallel set of presentations/interfaces to the same underlying data and business logic.

Behind the scenes (totally out of the scope of web services or UI layers), the business layer calls a data access layer that takes care of physically querying the database. If you were to change to a different DBMS, you should ideally (and in theory) be able to rebuild the data layer for the new database and have everything simply work.

Your business layer contains the rules like a username has to be 4 to 15 characters long; users are only allowed to search for and load products that are at a store they have access to; etc.

If you decide to change a business rule - like a user is allowed to search for products in any store in their state - then you change it in once place, and don't have to touch the web service or UI to make it work.

gregmac's user avatar

From your description, you haven't provided a reason why you would need the use of a web service layer. Assuming your database is reachable by your UI system, i.e. within the same network behind your firewall, a basic business-object layer that your website UI code (server-side, I'm assuming) will employ meets your requirements.

Bring in a web service tier when the distance between your UI system and your data layer starts to cross boundaries that a Data access layer or Business logic layer would begin to encounter difficulties.

jro's user avatar

In terms of the design being "correct" or not, it's not really possible to give a 100% answer to the correctness of a design without the full context. What are the requirements (functional and non-functional)? What design goals do you want to fulfill? How important is each goal?

The only goal your question mentions is that you want to reuse the business logic with another application. When I want to reuse the business logic of an application in a standard way I choose web services. So based solely on your one requirement I would say that option 1 ( UI->Web Service->Business Layer->Data Layer ) is a good choice.

Randy Levy's user avatar

Logically, web-services belong in the UI layer. Think of "User" being not only a human but another system and it becomes clear. Maintaining strict separation of concerns between these logical layers will allow you to easily implement and maintain your application.

user695683's user avatar

Check Out: http://www.icemanind.com/layergen.aspx

The way it should go is, you have your UI layer on top, your data layer on the bottom and your business layer in between the two. Each layer can only communicate with the layer below it. So the UI talks to the business layer only...the business layer talks to the data layer only. Your UI should never talk with the data layer and your data layer should never interact with your UI.

Unless you have a reason to use a web service, then I wouldn't.

Icemanind's user avatar

Do you hear anything about Service layer ? I think you can use a service layer for your transactions and operations and using a facade layer helps you to isolate and manage accessing from UI to data access layer directly or indirectly after visiting the Business layer . it depends on your requirements.

siamak's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

  • The Overflow Blog
  • Where does Postgres fit in a world of GenAI and vector databases?
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • Staging Ground Reviewer Motivation

Hot Network Questions

  • Does Vexing Bauble counter taxed 0 mana spells?
  • If inflation/cost of living is such a complex difficult problem, then why has the price of drugs been absoultly perfectly stable my whole life?
  • Do metal objects attract lightning?
  • Slicing Graph by path
  • My visit is for two weeks but my host bought insurance for two months is it okay
  • Distinctive form of "לאהוב ל-" instead of "לאהוב את"
  • Could someone tell me what this part of an A320 is called in English?
  • 2 in 1: Twin Puzzle
  • Cramer's Rule when the determinant of coefficient matrix is zero?
  • How can these humans cross the ocean(s) at the first possible chance?
  • How did Oswald Mosley escape treason charges?
  • Can probabilistic predictions be obtained from gradient boosting models CatBoost and XGBoost?
  • How do enable tagging in a `\list` based environment in `expl3`?
  • Who was the "Dutch author", "Bumstone Bumstone"?
  • Historical U.S. political party "realignments"?
  • Reference request: acceleration/curvature of curve in metric space
  • What is the name of this simulator
  • How do eradicated diseases make a comeback?
  • Why does flow separation cause an increase in pressure drag?
  • Why does a halfing's racial trait lucky specify you must use the next roll?
  • How long does it take to achieve buoyancy in a body of water?
  • What unique phenomena would be observed in a system around a hypervelocity star?
  • Correct Expression for Centripetal Force
  • Do the amplitude and frequency of gravitational waves emitted by binary stars change as the stars get closer together?

ui presentation layer

IMAGES

  1. Service-centric architecture with multiple presentation layers (user

    ui presentation layer

  2. UI layer

    ui presentation layer

  3. Flutter App Architecture: The Presentation Layer

    ui presentation layer

  4. Free Behance UI UX Presentation Template XD

    ui presentation layer

  5. Elements of ui design. Modern presentation with infographic, 3261625

    ui presentation layer

  6. UX UI Design presentation on Behance

    ui presentation layer

VIDEO

  1. OSI Model Layer 1 Physical

  2. What is Serverless Computing

  3. UI PRESENTATION THE WRATH OF SIMALUNGUN

  4. OSI model

  5. UI3 Features

  6. Enterprise Computing Year 12 Unit 2: Data Visualisation

COMMENTS

  1. Difference between presentation layer and user-interface

    0. The presentation layer delivers information to the application layer for display. The presentation layer, in some cases, handles data translation to allow use on a particular system. The user interface shows you the data once the presentation layer has done any translations it needs to.

  2. What Are the 5 Primary Layers in Software Architecture?

    Here are five main layers in software architecture: 1. Presentation layer. The presentation layer, also called the UI layer, handles the interactions that users have with the software. It's the most visible layer and defines the application's overall look and presentation to the end-users. This is the tier that's most accessible, which anyone ...

  3. Chapter 10

    The presentation layer contains the components that implement and display the user interface and manage user interaction. This layer includes controls for user input and display, in addition to components that organize user interaction. Figure 1 shows how the presentation layer fits into a common application architecture.

  4. App Architecture: Presentation layer

    App Architecture: Presentation layer. This is a series of articles about how to architecture your app that it was inspired by Google Guide to App Architecture and my personal experience. Today we finally explore the Presentation layer of our architecture. It contains all UI-related logic and everything the user can see and interact with.

  5. Multitier architecture

    In a logical multilayer architecture for an information system with an object-oriented design, the following four are the most common: . Presentation layer (a.k.a. UI layer, view layer, presentation tier in multitier architecture); Application layer (a.k.a. service layer [8] [9] or GRASP Controller Layer [10]); Business layer (a.k.a. business logic layer (BLL), domain logic layer)

  6. Presentation Layer in OSI model

    Prerequisite : OSI Model. Introduction : Presentation Layer is the 6th layer in the Open System Interconnection (OSI) model. This layer is also known as Translation layer, as this layer serves as a data translator for the network. The data which this layer receives from the Application Layer is extracted and manipulated here as per the required ...

  7. Web Application Architecture: How the Web Works

    The presentation layer is accessible to users via a browser and consists of user interface components and UI process components that support interaction with the system. It's developed using three core technologies: HTML, CSS, and JavaScript. While HTML is the code that determines what your website will contain, CSS controls how it will look.

  8. Software Architecture: The 5 Patterns You Need to Know

    Presentation or UI layer; Application layer; Business or domain layer; Persistence or data access layer; Database layer; The idea is that the user initiates a piece of code in the presentation layer by performing some action (e.g. clicking a button). The presentation layer then calls the underlying layer, i.e. the application layer.

  9. Angular Architecture

    Presentation layer The presentation layer (UI) layer is where all Angular components reside. Its primary responsibility is to present the application's UI and delegate user actions to the core layer through the abstraction layer. Inside of presentation layer we have: Smart/container components: can pass data down to dumb components

  10. Defining Presentation and Visualization Layer

    Step-by-step Presentation Layer Accessing the UI layer Higher-Order Component. ... Our supposed Presentation Layer contains the business rule of the application, ...

  11. App Architecture: Presentation layer

    The Presentation layer also has its data models that reflect models from the Domain layer but are more UI-specific. The mapping logic of the presentation model to the domain and vice versa should be placed in the ViewModel class. The presentation layer shouldn't expose the UI model to other layers.

  12. Why should I isolate my domain entities from my presentation layer?

    Your presentation may reference your domain layer, but there should be no binding directly from your ui to your domain objects. Domain objects are not intended for UI usage since they are often, if properly designed, based around behaviors and not data representations. There should be a mapping layer between the UI and the Domain.

  13. Comparing Three-Layered and Clean Architecture for Web Development

    Classic three-layer architecture. UI or presentation layer. This is the layer with which the user directly interacts. This layer is a user interface, the mechanism for getting input from the user. It may contain controllers and view models, as well as views that make up the user interface (HTML static pages, JavaScript). Business logic layer.

  14. Clean Architecture Guide (with tested examples): Data Flow ...

    Clean Architecture Layers. Let's identify the different layers & boundaries. Presentation Layer contains UI (Activities & Fragments) that are coordinated by Presenters/ViewModels which execute 1 or multiple Use cases. Presentation Layer depends on Domain Layer. Domain Layer is the most INNER part of the onion (no dependencies with other layers) and it contains Entities, Use cases ...

  15. UI layer

    Because the role of the data layer is to hold, manage, and provide access to the app data, the UI layer must perform the following steps: Consume app data and transform it into data the UI can easily render. Consume UI-renderable data and transform it into UI elements for presentation to the user. Consume user input events from those assembled ...

  16. A Primer on Layers: Understanding Layer-Based Architectures

    UI layer, where the presentation takes place; A storage layer where the persistence of the data takes place; 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.

  17. Presentation Domain Data Layering

    One of the most common ways to modularize an information-rich program is to separate it into three broad layers: presentation (UI), domain logic (aka business logic), and data access. So you often see web applications divided into a web layer that knows about handling HTTP requests and rendering HTML, a business logic layer that contains ...

  18. Application Architecture Guide

    Presentation layer components implement the functionality required to allow users to interact with the application. The following types of components are commonly found in the presentation layer: User interface (UI) components. These components provide the mechanism for users to interact with the application. They format data and render it for ...

  19. architecture

    In this design the UI/Presentation layer and the application layer are clearly separated. Merging the 2 together introduces tight coupling between 2 layers that have clear separate concerns and responsibilities. The Presentation layer should only house presentation logic. Avoid Smart UIs that know too much.

  20. Breaking Down the Layers: Understanding the Four-tier Software

    The first layer of the four-tier architecture is the presentation layer, also known as the user interface layer. This layer is responsible for presenting information to the user and receiving user input. It includes components such as web pages, forms, and graphical user interfaces. The presentation layer communicates with the business logic ...

  21. Guide to app architecture

    UI layer. The role of the UI layer (or presentation layer) is to display the application data on the screen. Whenever the data changes, either due to user interaction (such as pressing a button) or external input (such as a network response), the UI should update to reflect the changes. The UI layer is made up of two things:

  22. How many layers should be used inside a Microservice?

    The Presentation layer translates between the UI and the Domain layer: User input is transformed into business functions and results from business functions are represented in a user friendly view ...

  23. UI, Business Logic Layer, Data Layer and where to put web services

    I would say the 3rd one. I tend to think of web services as another presentation layer. Think of it this way: you have a web UI, which calls your business layer code to do things like create a new user (User.Add), find all products that match a given description (Products.FindByDescription), etc.