Illustration with collage of pictograms of computer monitor, server, clouds, dots

Three-tier architecture is a well-established software application architecture that organizes applications into three logical and physical computing tiers: the presentation tier, or user interface; the application tier, where data is processed; and the data tier, where application data is stored and managed.

The chief benefit of three-tier architecture is that because each tier runs on its own infrastructure, each tier can be developed simultaneously by a separate development team. And can be updated or scaled as needed without impacting the other tiers.

For decades three-tier architecture was the prevailing architecture for client-server applications. Today, most three-tier applications are targets for modernization that uses cloud-native technologies such as containers and microservices and for migration to the cloud.

Connect and integrate your systems to prepare your infrastructure for AI.

Register for the guide on app modernization

Presentation tier

The presentation tier is the user interface and communication layer of the application, where the end user interacts with the application. Its main purpose is to display information to and collect information from the user. This top-level tier can run on a web browser, as desktop application, or a graphical user interface (GUI), for example. Web presentation tiers are developed by using HTML, CSS, and JavaScript. Desktop applications can be written in various languages depending on the platform.

Application tier

The application tier, also known as the logic tier or middle tier, is the heart of the application. In this tier, information that is collected in the presentation tier is processed - sometimes against other information in the data tier - using business logic, a specific set of business rules. The application tier can also add, delete, or modify data in the data tier. 

The application tier is typically developed by using Python, Java, Perl, PHP or Ruby, and communicates with the data tier by using  API  calls. 

The data tier, sometimes called database tier, data access tier or back-end, is where the information that is processed by the application is stored and managed. This can be a  relational database management system  such as  PostgreSQL , MySQL, MariaDB, Oracle, Db2, Informix or Microsoft SQL Server, or in a  NoSQL  Database server such as Cassandra,  CouchDB , or  MongoDB . 

In a three-tier application, all communication goes through the application tier. The presentation tier and the data tier cannot communicate directly with one another.

Tier versus layer

In discussions of three-tier architecture,  layer  is often used interchangeably – and mistakenly – for  tier , as in 'presentation layer' or 'business logic layer'. 

They aren't the same. A 'layer' refers to a functional division of the software, but a 'tier' refers to a functional division of the software that runs on infrastructure separate from the other divisions. The Contacts app on your phone, for example, is a  three - layer  application, but a  single-tier  application, because all three layers run on your phone.

The difference is important because layers can't offer the same benefits as tiers.

Again, the chief benefit of three-tier architecture is its logical and physical separation of functionality. Each tier can run on a separate operating system and server platform - for example, web server, application server, database server - that best fits its functional requirements. And each tier runs on at least one dedicated server hardware or virtual server, so the services of each tier can be customized and optimized without impacting the other tiers. 

Other benefits (compared to single- or two-tier architecture) include:

  • Faster development : Because each tier can be developed simultaneously by different teams, an organization can bring the application to market faster. And programmers can use the latest and best languages and tools for each tier.
  • Improved scalability : Any tier can be scaled independently of the others as needed.
  • Improved reliability : An outage in one tier is less likely to impact the availability or performance of the other tiers.
  • Improved security : Because the presentation tier and data tier can't communicate directly, a well-designed application tier can function as an internal firewall, preventing SQL injections and other malicious exploits.

In web development, the tiers have different names but perform similar functions:

  • The web server  is the presentation tier and provides the user interface. This is usually a web page or website, such as an ecommerce site where the user adds products to the shopping cart, adds payment details or creates an account. The content can be static or dynamic, and is developed using HTML, CSS, and JavaScript.
  • The application server  corresponds to the middle tier, housing the business logic that is used to process user inputs. To continue the ecommerce example, this is the tier that queries the inventory database to return product availability, or adds details to a customer's profile. This layer often developed using Python, Ruby, or PHP and runs a framework such as Django, Rails, Symphony, or ASP.NET.
  • The database server  is the data or backend tier of a web application. It runs on database management software, such as MySQL, Oracle, DB2, or PostgreSQL.

While three-tier architecture is easily the most widely adopted multitier application architecture, there are others that you might encounter in your work or your research.

Two-tier architecture 

Two-tier architecture is the original client-server architecture, consisting of a presentation tier and a data tier; the business logic lives in the presentation tier, the data tier or both. In two-tier architecture the presentation tier - and therefore the end user - has direct access to the data tier, and the business logic is often limited. A simple contact management application, where users can enter and retrieve contact data, is an example of a two-tier application. 

N-tier architecture

N-tier architecture - also called or multitier architecture - refers to  any  application architecture with more than one tier. But applications with more than three layers are rare because extra layers offer few benefits and can make the application slower, harder to manage and more expensive to run. As a result, n-tier architecture and multitier architecture are usually synonyms for three-tier architecture.

Move to cloud faster with IBM Cloud Pak solutions running on Red Hat OpenShift software—integrated, open, containerized solutions certified by IBM®.

Seamlessly modernize your VMware workloads and applications with IBM Cloud.

Modernize, build new apps, reduce costs, and maximize ROI.

IBM Consulting® application modernization services, which are powered by IBM Consulting Cloud Accelerator, offers skills, methods, tools, and initiatives that help determine the right strategy based on your portfolio. To modernize and containerize legacy system applications and accelerate the time-to-value of hybrid cloud environments. 

Discover what application modernization is, the common benefits and challenges, and how to get started.

Learn about how relational databases work and how they compare to other data storage options.

Explore cloud native applications and how they drive innovation and speed within your enterprise.

Modernize your legacy three-tier applications on your journey to cloud. Whether you need assistance with strategy, processes, or capabilities—or want full-service attention—IBM can help. Start using containerized middleware that can run in any cloud—all bundled in IBM Cloud Paks.

Application Architecture Guide - Chapter 10 - Presentation Layer Guidelines

Note - The patterns & practices Microsoft Application Architecture Guide, 2nd Edition is now live at http://msdn.microsoft.com/en-us/library/dd673617.aspx .

- J.D. Meier, Alex Homer, David Hill, Jason Taylor, Prashant Bansode, Lonnie Wall, Rob Boucher Jr, Akshay Bogawat

  • 1 Objectives
  • 3 Presentation Layer Components
  • 5 Design Considerations
  • 6 Presentation Layer Frame
  • 8 Composition
  • 9 Exception Management
  • 12 Navigation
  • 13 Presentation Entities
  • 14 Request Processing
  • 15 User Experience
  • 16 UI Components
  • 17 UI Process Components
  • 18 Validation
  • 19 Pattern Map
  • 20 Pattern Descriptions
  • 21.1 Mobile Applications
  • 21.2 Rich Client Applications
  • 21.3 Rich Internet Applications (RIA)
  • 21.4 Web Applications
  • 22 patterns & practices Solution Assets
  • 23 Additional Resources
  • Understand how the presentation layer fits into typical application architecture.
  • Understand the components of the presentation layer.
  • Learn the steps for designing the presentation layer.
  • Learn the common issues faced while designing the presentation layer.
  • Learn the key guidelines for designing the presentation layer.
  • Learn the key patterns and technology considerations for designing the presentation layer.

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.

ui presentation layer

Figure 1 A typical application showing the presentation layer and the components it may contain

Presentation Layer Components

  • User interface (UI) components . User interface components provide a way for users to interact with the application. They render and format data for users. They also acquire and validate data input by the user.
  • User process components . User process components synchronize and orchestrate user interactions. Separate user process components may be useful if you have a complicated UI. Implementing common user interaction patterns as separate user process components allows you to reuse them in multiple UIs.

The following steps describe the process you should adopt when designing the presentation layer for your application. This approach will ensure that you consider all of the relevant factors as you develop your architecture:

  • Identify your client type . Choose a client type that satisfies your requirements and adheres to the infrastructure and deployment constraints of your organization. For instance, if your users are on mobile devices and will be intermittently connected to the network, a mobile rich client is probably your best choice.
  • Determine how you will present data . Choose the data format for your presentation layer and decide how you will present the data in your UI.
  • Determine your data-validation strategy . Use data-validation techniques to protect your system from untrusted input.
  • Determine your business logic strategy . Factor out your business logic to decouple it from your presentation layer code.
  • Determine your strategy for communication with other layers . If your application has multiple layers, such as a data access layer and a business layer, determine a strategy for communication between your presentation layer and other layers.

Design Considerations

There are several key factors that you should consider when designing your presentation layer. Use the following principles to ensure that your design meets the requirements for your application, and follows best practices:

  • Choose the appropriate UI technology. Determine if you will implement a rich (smart) client, a Web client, or a rich Internet application (RIA). Base your decision on application requirements, and on organizational and infrastructure constraints.
  • Use the relevant patterns. Review the presentation layer patterns for proven solutions to common presentation problems.
  • Design for separation of concerns. Use dedicated UI components that focus on rendering and display. Use dedicated presentation entities to manage the data required to present your views. Use dedicated UI process components to manage the processing of user interaction.
  • Consider human interface guidelines. Review your organization’s guidelines for UI design. Review established UI guidelines based on the client type and technologies that you have chosen.
  • Adhere to user-driven design principles. Before designing your presentation layer, understand your customer. Use surveys, usability studies, and interviews to determine the best presentation design to meet your customer’s requirements.

Presentation Layer Frame

There are several common issues that you must consider as your develop your design. These issues can be categorized into specific areas of the design. The following table lists the common issues for each category where mistakes are most often made.

Table 1 Presentation Layer Frame

Caching is one of the best mechanisms you can use to improve application performance and UI responsiveness. Use data caching to optimize data lookups and avoid network round trips. Cache the results of expensive or repetitive processes to avoid unnecessary duplicate processing.

Consider the following guidelines when designing your caching strategy:

  • Do not cache volatile data.
  • Consider using ready-to-use cache data when working with an in-memory cache. For example, use a specific object instead of caching raw database data.
  • Do not cache sensitive data unless you encrypt it.
  • If your application is deployed in Web farm, avoid using local caches that need to be synchronized; instead, consider using a transactional resource manager such as Microsoft SQL Server® or a product that supports distributed caching.
  • Do not depend on data still being in your cache. It may have been removed.

Composition

Consider whether your application will be easier to develop and maintain if the presentation layer uses independent modules and views that are easily composed at run time. Composition patterns support the creation of views and the presentation layout at run time. These patterns also help to minimize code and library dependencies that would otherwise force recompilation and redeployment of a module when the dependencies change. Composition patterns help you to implement sharing, reuse, and replacement of presentation logic and views.

Consider the following guidelines when designing your composition strategy:

  • Avoid using dynamic layouts. They can be difficult to load and maintain.
  • Be careful with dependencies between components. For example, use abstraction patterns when possible to avoid issues with maintainability.
  • Consider creating templates with placeholders. For example, use the Template View pattern to compose dynamic Web pages in order to ensure reuse and consistency.
  • Consider composing views from reusable modular parts. For example, use the Composite View pattern to build a view from modular, atomic component parts.
  • If you need to allow communication between presentation components, consider implementing the Publish/Subscribe pattern. This will lower the coupling between the components and improve testability.

Exception Management

Design a centralized exception-management mechanism for your application that catches and throws exceptions consistently. Pay particular attention to exceptions that propagate across layer or tier boundaries, as well as exceptions that cross trust boundaries. Design for unhandled exceptions so they do not impact application reliability or expose sensitive information.

Consider the following guidelines when designing your exception management strategy:

  • Use user-friendly error messages to notify users of errors in the application.
  • Avoid exposing sensitive data in error pages, error messages, log files, and audit files.
  • Design a global exception handler that displays a global error page or an error message for all unhandled exceptions.
  • Differentiate between system exceptions and business errors. In the case of business errors, display a user-friendly error message and allow the user to retry the operation. In the case of system exceptions, check to see if the exception was caused by issues such as system or database failure, display a user-friendly error message, and log the error message, which will help in troubleshooting.
  • Avoid using exceptions to control application logic.

Design a user input strategy based on your application input requirements. For maximum usability, follow the established guidelines defined in your organization, and the many established industry usability guidelines based on years of user research into input design and mechanisms.

Consider the following guidelines when designing your input collection strategy:

  • Use forms-based input controls for normal data-collection tasks.
  • Use a document-based input mechanism for collecting input in Microsoft Office–style documents.
  • Implement a wizard-based approach for more complex data collection tasks, or for input that requires a workflow.
  • Design to support localization by avoiding hard-coded strings and using external resources for text and layout.
  • Consider accessibility in your design. You should consider users with disabilities when designing your input strategy; for example, implement text-to-speech software for blind users, or enlarge text and images for users with poor sight. Support keyboard-only scenarios where possible for users who cannot manipulate a pointing device.

Design your UI layout so that the layout mechanism itself is separate from the individual UI components and UI process components. When choosing a layout strategy, consider whether you will have a separate team of designers building the layout, or whether the development team will create the UI. If designers will be creating the UI, choose a layout approach that does not require code or the use of development-focused tools.

Consider the following guidelines when designing your layout strategy:

  • Use templates to provide a common look and feel to all of the UI screens.
  • Use a common look and feel for all elements of your UI to maximize accessibility and ease of use.
  • Consider device-dependent input, such as touch screens, ink, or speech, in your layout. For example, with touch-screen input you will typically use larger buttons with more spacing between them than you would with mouse or keyboard inputs.
  • When building a Web application, consider using Cascading Style Sheets (CSS) for layout. This will improve rendering performance and maintainability.
  • Use design patterns, such as Model-View-Presenter (MVP), to separate the layout design from interface processing.

Design your navigation strategy so that users can navigate easily through your screens or pages, and so that you can separate navigation from presentation and UI processing. Ensure that you display navigation links and controls in a consistent way throughout your application to reduce user confusion and hide application complexity.

Consider the following guidelines when designing your navigation strategy:

  • Use well-known design patterns to decouple the UI from the navigation logic where this logic is complex.
  • Design toolbars and menus to help users find functionality provided by the UI.
  • Consider using wizards to implement navigation between forms in a predictable way.
  • Determine how you will preserve navigation state if the application must preserve this state between sessions.
  • Consider using the Command Pattern to handle common actions from multiple sources.

Presentation Entities

Use presentation entities to store the data you will use in your presentation layer to manage your views. Presentation entities are not always necessary; use them only if your datasets are sufficiently large and complex to require separate storage from the UI controls.

Consider the following guidelines when designing presentation entities:

  • Determine if you require presentation entities. Typically, you may require presentation entities only if the data or the format to be displayed is specific to the presentation layer.
  • If you are working with data-bound controls, consider using custom objects, collections, or datasets as your presentation entity format.
  • If you want to map data directly to business entities, use a custom class for your presentation entities.
  • Do not add business logic to presentation entities.
  • If you need to perform data type validation, consider adding it in your presentation entities.

Request Processing

Design your request processing with user responsiveness in mind, as well as code maintainability and testability.

Consider the following guidelines when designing request processing:

  • Use asynchronous operations or worker threads to avoid blocking the UI for long-running actions.
  • Avoid mixing your UI processing and rendering logic.
  • Consider using the Passive View pattern (a variant of MVP) for interfaces that do not manage a lot of data.
  • Consider using the Supervising Controller pattern (a variant of MVP) for interfaces that manage large amounts of data.

User Experience

Good user experience can make the difference between a usable and unusable application. Carry out usability studies, surveys, and interviews to understand what users require and expect from your application, and design with these results in mind.

Consider the following guidelines when designing for user experience:

  • When developing a rich Internet application (RIA), avoid synchronous processing where possible.
  • When developing a Web application, consider using Asynchronous JavaScript and XML (AJAX) to improve responsiveness and to reduce post backs and page reloads.
  • Do not design overloaded or overly complex interfaces. Provide a clear path through the application for each key user scenario.
  • Design to support user personalization, localization, and accessibility.
  • Design for user empowerment. Allow the user to control how he or she interacts with the application, and how it displays data to them.

UI Components

UI components are the controls and components used to display information to the user and accept user input. Be careful not to create custom controls unless it is necessary for specialized display or data collection.

Consider the following guidelines when designing UI components:

  • Take advantage of the data-binding features of the controls you use in the UI.
  • Create custom controls or use third-party controls only for specialized display and data-collection tasks.
  • When creating custom controls, extend existing controls if possible instead of creating a new control.
  • Consider implementing designer support for custom controls to make it easier to develop with them.
  • Consider maintaining the state of controls as the user interacts with the application instead of reloading controls with each action.

UI Process Components

UI process components synchronize and orchestrate user interactions. UI processing components are not always necessary; create them only if you need to perform significant processing in the presentation layer that must be separated from the UI controls. Be careful not to mix business and display logic within the process components; they should be focused on organizing user interactions with your UI.

Consider the following guidelines when designing UI processing components:

  • Do not create UI process components unless you need them.
  • If your UI requires complex processing or needs to talk to other layers, use UI process components to decouple this processing from the UI.
  • Consider dividing UI processing into three distinct roles: Model, View, and Controller/Presenter, by using the MVC or MVP pattern.
  • Avoid business rules, with the exception of input and data validation, in UI processing components.
  • Consider using abstraction patterns, such as dependency inversion, when UI processing behavior needs to change based on the run-time environment.
  • Where the UI requires complex workflow support, create separate workflow components that use a workflow system such as Windows Workflow or a custom mechanism.

Designing an effective input and data-validation strategy is critical to the security of your application. Determine the validation rules for user input as well as for business rules that exist in the presentation layer.

Consider the following guidelines when designing your input and data validation strategy:

  • Validate all input data on the client side where possible to improve interactivity and reduce errors caused by invalid data.
  • Do not rely on client-side validation only. Always use server-side validation to constrain input for security purposes and to make security-related decisions.
  • Design your validation strategy to constrain, reject, and sanitize malicious input.
  • Use the built-in validation controls where possible, when working with .NET Framework.
  • In Web applications, consider using AJAX to provide real-time validation.

Pattern Map

Key patterns are organized by key categories, as detailed in the Presentation Layer Frame in the following table. Consider using these patterns when making design decisions for each category.

Table 2 Pattern Map

  • For more information on the Page Cache pattern, see “Enterprise Solution Patterns Using Microsoft .NET” at http://msdn.microsoft.com/en-us/library/ms998469.aspx
  • For more information on the Model-View-Controller (MVC), Page Controller, Front Controller, Template View, Transform View, and Two-Step View patterns, see “Patterns of Enterprise Application Architecture (P of EAA)” at http://martinfowler.com/eaaCatalog/
  • For more information on the Composite View, Supervising Controller, and Presentation Model patterns, see “Patterns in the Composite Application Library” at http://msdn.microsoft.com/en-us/library/cc707841.aspx
  • For more information on the Chain of responsibility and Command pattern, see “data & object factory” at http://www.dofactory.com/Patterns/Patterns.aspx
  • For more information on the Asynchronous Callback pattern, see “Creating a Simplified Asynchronous Call Pattern for Windows Forms Applications” at http://msdn.microsoft.com/en-us/library/ms996483.aspx
  • For more information on the Exception Shielding and Entity Translator patterns, see “Useful Patterns for Services” at http://msdn.microsoft.com/en-us/library/cc304800.aspx

Pattern Descriptions

  • Asynchronous Callback. Execute long-running tasks on a separate thread that executes in the background, and provide a function for the thread to call back into when the task is complete.
  • Cache Dependency. Use external information to determine the state of data stored in a cache.
  • Chain of Responsibility. Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request.
  • Composite View . Combine individual views into a composite representation.
  • Command Pattern. Encapsulate request processing in a separate command object with a common execution interface.
  • Entity Translator. An object that transforms message data types into business types for requests, and reverses the transformation for responses.
  • Exception Shielding. Prevent a service from exposing information about its internal implementation when an exception occurs.
  • Front Controller . Consolidate request handling by channeling all requests through a single handler object, which can be modified at run time with decorators.
  • Model-View-Controller . Separate the UI code into three separate units: Model (data), View (interface), and Presenter (processing logic), with a focus on the View. Two variations on this pattern include Passive View and Supervising Controller, which define how the View interacts with the Model.
  • Page Cache. Improve the response time for dynamic Web pages that are accessed frequently but change less often and consume a large amount of system resources to construct.
  • Page Controller . Accept input from the request and handle it for a specific page or action on a Web site.
  • Passive View . Reduce the view to the absolute minimum by allowing the controller to process user input and maintain the responsibility for updating the view.
  • Presentation Model . Move all view logic and state out of the view, and render the view through data-binding and templates.
  • Supervising Controller . A variation of the MVC pattern in which the controller handles complex logic, in particular coordinating between views, but the view is responsible for simple view-specific logic.
  • Template View . Implement a common template view, and derive or construct views using this template view.
  • Transform View . Transform the data passed to the presentation tier into HTML for display in the UI.
  • Two-Step View . Transform the model data into a logical presentation without any specific formatting, and then convert that logical presentation to add the actual formatting required.

Technology Considerations

The following guidelines will help you to choose an appropriate implementation technology. The guidelines also contain suggestions for common patterns that are useful for specific types of application and technology.

Mobile Applications

Consider the following guidelines when designing a mobile application:

  • If you want to build full-featured connected, occasionally connected, and disconnected executable applications that run on a wide range of Microsoft Windows®–based devices, consider using the Microsoft Windows Compact Framework.
  • If you want to build connected applications that require Wireless Application Protocol (WAP), compact HTML (cHTML), or similar rendering formats, consider using ASP.NET Mobile Forms and Mobile Controls.
  • If you want to build applications that support rich media and interactivity, consider using Microsoft Silverlight® for Mobile.

Rich Client Applications

Consider the following guidelines when designing a rich client application:

  • If you want to build applications with good performance and interactivity, and have design support in Microsoft Visual Studio®, consider using Windows Forms.
  • If you want to build applications that fully support rich media and graphics, consider using Windows Presentation Foundation (WPF).
  • If you want to build applications that are downloaded from a Web server and then execute on the client, consider using XAML Browser Applications (XBAP).
  • If you want to build applications that are predominantly document-based, or are used for reporting, consider designing a Microsoft Office Business Application.
  • If you decide to use Windows Forms and you are designing composite interfaces, consider using the Smart Client Software Factory.
  • If you decide to use WPF and you are designing composite interfaces, consider using the Composite Application Guidance for WPF.
  • If you decide to use WPF, consider using the Presentation Model (Model-View-ViewModel) pattern.
  • If you decide to use WPF, consider using WPF Commands to communicate between your View and your Presenter or ViewModel.
  • If you decide to use WPF, consider implementing the Presentation Model pattern by using DataTemplates over User Controls to give designers more control.

Rich Internet Applications (RIA)

Consider the following guidelines when designing an RIA:

  • If you want to build browser-based, connected applications that have broad cross-platform reach, are highly graphical, and support rich media and presentation features, consider using Silverlight.
  • If you decide to use Silverlight, consider using the Presentation Model (Model-View-ViewModel) pattern.

Web Applications

Consider the following guidelines when designing a Web application:

  • If you want to build applications that are accessed through a Web browser or specialist user agent, consider using ASP.NET.
  • If you want to build applications that provide increased interactivity and background processing, with fewer page reloads, consider using ASP.NET with AJAX.
  • If you want to build applications that include islands of rich media content and interactivity, consider using ASP.NET with Silverlight controls.
  • If you are using ASP.NET and want to implement a control-centric model with separate controllers and improved testability, consider using the ASP.NET MVC Framework.
  • If you are using ASP.NET, consider using master pages to simplify development and implement a consistent UI across all pages.

patterns & practices Solution Assets

  • Web Client Software Factory at http://msdn.microsoft.com/en-us/library/bb264518.aspx
  • Smart Client Software Factory at http://msdn.microsoft.com/en-us/library/aa480482.aspx
  • Composite Application Guidance for WPF at http://msdn.microsoft.com/en-us/library/cc707819.aspx
  • Smart Client - Composite UI Application Block at http://msdn.microsoft.com/en-us/library/aa480450.aspx

Additional Resources

  • For more information, see Microsoft Inductive User Interface Guidelines at http://msdn.microsoft.com/en-us/library/ms997506.aspx .
  • For more information, see User Interface Control Guidelines at http://msdn.microsoft.com/en-us/library/bb158625.aspx .
  • For more information, see User Interface Text Guidelines at http://msdn.microsoft.com/en-us/library/bb158574.aspx .
  • For more information, see Design and Implementation Guidelines for Web Clients at http://msdn.microsoft.com/en-us/library/ms978631.aspx .
  • For more information, see Web Presentation Patterns at http://msdn.microsoft.com/en-us/library/ms998516.aspx .

Navigation menu

Page actions.

  • View source

Personal tools

  • Community portal
  • Current events
  • Recent changes
  • Random page
  • What links here
  • Related changes
  • Special pages
  • Printable version
  • Permanent link
  • Page information

Powered by MediaWiki

  • This page was last edited on 22 January 2010, at 02:50.
  • Privacy policy
  • About Guidance Share
  • Disclaimers
  • 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.

  • How we work
  • Let’s talk →

The mobile app architecture guide

ui presentation layer

When you hear the word architecture , what is it that immediately comes to mind?

Most likely, it’s your house. And that’s natural.

Architecture simply refers to the internal structure of something—be it an office building or your car.

Mobile apps have their own architecture, too.

In fact, architecture is one of the most important factors in development because it greatly impacts app efficiency, stability, and security.

This article will discuss some common types of app architecture and why they’re important in app development.

Table of Contents

What is mobile app architecture?

In app development, architecture refers to an app’s rules, processes, and internal structure—essentially, how it’s built.

It determines how the different components communicate with each other to process app inputs and deliver output for the user.

Here’s an example of what mobile architecture looks like:

Mobile architecture

A good analogy for this is the human body. All your body parts are arranged in a way that allows you to move, breathe, and otherwise perform efficiently.

Any changes in the structure of your organs would affect the body irreversibly—even get it to shut down completely.

The same is true with mobile app architecture.

Now, you shouldn’t confuse app architecture with a tech stack—although they’re related.

Tech stack refers to the technologies and tools used to build an app, such as programming languages, third-party plug-ins, and hardware platforms.

On the other hand, architecture describes how these technologies are arranged inside the app.

Furthermore, it goes beyond the tools and into the other parts of the app, such as the data and the users.

Put another way, the tech stack is simply one aspect of mobile app architecture.

Why is the architecture of a mobile app important?

Simply put, properly designed architecture makes the mobile app much more stable, efficient, and easier to work with.

One of the main benefits of app architecture is modularity . It means your app is divided into components that can be developed, updated, and tested independently.

Martin Fowler , an esteemed software developer, highlighted the benefits of modularity clearly when he said:

A good architecture is important, otherwise it becomes slower and more expensive to add new capabilities in the future.

For example, suppose you want to introduce a new feature to your app.

When you’re dealing with modular architecture, it’s simple. Just code the new feature separately, then integrate it into the existing app.

Otherwise, you’ll need to modify the entire app, which is costly and time-consuming.

Modularised app architecture

Thanks to modularity, good architecture also allows for reusability . This allows you to use a single code in multiple projects, saving you tremendous development time and effort.

For instance, you can reuse a database management component on multiple apps that share the same database system.

Or, you can adapt a sorting algorithm from a previous project instead of creating it from scratch.

App architecture is also crucial for improving security . That’s because it allows you to compartmentalize sensitive data and code, then build security protocols around them.

For instance, you can put SSL encryption between the client machine and the code logic in the web server.

You could then boost your data security further by adding a layer of encryption around your database.

Data security using SSL Encryption

Ultimately, well-devised app architecture helps you deliver a safe and bug-free app while saving you time and money in the process.

Fundamental layers in mobile app architecture

Most types of app architecture are composed of three layers—the data layer, the business layer, and the presentation layer.

Here’s how they go together:

Let’s discuss each layer briefly.

The data layer is the intermediary between the other app layers and external resources.

Its main purpose is gathering raw data from various sources (such as the database, cloud server, or an API) and then sending it to the upper layers, and vice versa.

For example, when a user requests the app to display their profile, the data layer connects to the database and asks for all the relevant data such as name, birthday, photo file, and others.

However, the data is still unprocessed at this point, so it might contain attributes like tags or IDs that the user shouldn’t see. The responsibility of cleaning this data falls to the business layer.

Since raw data is highly vulnerable and sensitive, the data layer should have ample security.

Proper data segregation from various sources is critical here, as mixing them is considered bad practice.

Business layer

The business layer contains the application’s core logic—the exact instructions on how it should behave.

It often takes user input or raw data from the data layer, processes it, then sends it to the presentation layer.

As an example, take a simple calculator app. When you use it to add two numbers, it’s the business layer that performs the actual computation.

The answer is then sent to the UI to be displayed.

The business layer is the most complex part of your app. It’s usually divided into multiple sublayers or components, each responsible for specific functionality.

For instance, if you have an enterprise resource management (ERP) app, the business layer might have components for warehouse and inventory management.

Also, note that the business layer doesn’t necessarily have to be in the user’s app. Some or all of it can be contained in the server, with the app acting mostly as the UI.

Presentation layer

The presentation layer, or front end, is the visible part of the app—the part that the user actually sees. As you can guess, the app’s user interface (UI) is a big part of this layer.

The main purpose of the presentation layer is to take the data sent by the business layer and display it in a way the user understands.

A simple example is the UI displaying a user’s email address, which is extracted by the data layer from a database.

However, the presentation layer can also use the data and display it in complex ways.

A good example is a stock trading app. It takes live data about the stock exchange (from an external website via an API) and displays it as a graph or chart.

Stock trading app UI

While developers are mostly responsible for the business and data layers, the presentation layer is the domain of the UI and UX designer.

Their goal is to make the UI screens as user-friendly as possible.

Types of mobile app architecture

This section will discuss the three common types of mobile app architecture, including their pros, cons, and use cases.

Layered architecture

Layered or N-tier architecture is where components with similar logic or purpose are grouped, then organized into several layers or tiers.

This is the type of architecture typically used for on-premise software.

N-tier applications usually include the three layers we discussed before—data, business (or application), and presentation.

However, some apps can rely on four or five-layer architecture, depending on the circumstances.

Here’s an example of a five-tier app:

Five layer architecture

Layers can only interact or pass data to and from an adjacent layer. This is one of the key principles of this type of architecture, as it helps manage dependencies and enforce security.

For example, the client layer can’t directly access the data layer because that would be risky.

Instead, it has to pass through the business and integration layers, which contain the necessary safeguards and security checks.

N-layered architecture is generally easy to understand and manage—but only to a point. With larger apps, it gets harder to pinpoint which layer an error comes from.

Often, this involves troubleshooting multiple layers.

Monolithic architecture

In the monolithic type of architecture, all the app components are tightly integrated, and function as a single unit called a monolith. It’s an approach that you’ll often see in older systems.

The biggest reason to use monolithic architecture is simplicity. Since a monolith has fewer moving parts, it’s easier for developers to create, test, and deploy it as a self-contained app.

As such, monoliths are best for smaller, less complex apps or if you’re a start-up on a tight budget.

Otherwise, monolithic apps aren’t recommended because they’re extremely limiting.

If you want to change a feature or introduce a new one, you’d need to modify the entire codebase because everything is interconnected.

This makes updating and scaling them exceptionally costly and time-consuming.

You’re better off either with a layered or a microservices approach.

Microservices architecture

The microservices type of architecture divides the app into smaller components called a microservice.

Each microservice is completely standalone and can function without needing any other component.

The main client app then uses an application programming interface (API) to communicate with them, as shown below:

Microservices architecture represents the most flexible and fluid approach to developing software.

That’s because each app functionality can be developed, tested, and deployed independently.

Adding or editing new features is trivial—you just need to modify the relevant microservice, then have the client app call it via the API.

Microservices enable development teams to scale, fix, and upgrade apps rapidly.

However, the big drawback is that microservices architecture can be tricky to deploy since you must do it multiple times for each microservice. This gets trickier the larger the application.

Nevertheless, microservices are the best approach for developing complex cloud and hybrid applications.

Types of mobile app architecture patterns

Another way to define app architecture is through the pattern model. Let’s discuss the three common types to give you a better idea.

Model-View-Controller

The Model-View-Controller (MVC) is the simplest architecture pattern.

Here’s how it looks:

The Model component is responsible for data handling, similar to the data layer. It contains the code for getting data from sources like a database, a microservice via an API, or a JSON object.

The Controller component processes the data from the model component and sends it to the view component, essentially acting as the link between them.

This is where your app’s core logic and algorithms are contained.

The View component is responsible for what the user sees—or the UI.

The MVC architecture is the default for iOS apps, which explains its popularity. Its simplicity is one of its advantages.

However, here at DECODE, we realized over time  that MVC could become tedious and unwieldy for large, complex apps.

Model-View-Presenter

The Model-View-Presenter (MVP) architecture is another common pattern used extensively in Android development.

It looks like this:

The MVP architecture has many similarities with MVC. Here, the Model component also handles the data, and the View component is for the UI.

The Presenter component is analogous to the Controller component in the MVC model, containing the logic that processes data for the user.

However, a big difference is that in the MVP model, the View component is in charge .

That means it initiates requests to the Presenter and Model. In the MVC architecture, the Controller is in charge.

Thus, Views are reusable in the MVP model, which makes it more modular and reusable than an MVC application.

Model-View-ViewModel

The Model-View-ViewModel (MVVM) architecture separates the code logic as follows:

View, as always, houses the visual elements like UI and text. However, unlike the MVC and MVP models, the View component can’t change the UI elements directly.

Instead, the MVVM uses data binding for this purpose. It acts as the bridge between the View and ViewModel components.

The ViewModel contains the application logic, while the Model handles the data.

What this means is that the ViewModel can effectively work without having to know the View component.

This leads to a higher separation of logic, making an MVVM app easier to maintain than MVP and MVC, which is why we use it at DECODE .

So, which type of architecture should you choose?

We hope you’ve gained a sense of understanding and appreciation for different types of mobile app architecture.

Of course, this begs the practical question—which type of architecture is right for your app?

Unfortunately, there’s no general answer to that. It will depend on the circumstances of your project.

Instead, why not give us a call?

Schedule a FREE consultation  (fully backed by an NDA), and let’s figure out the best approach for your project!

Toni Vujevic

React native team lead.

Skilled in React Native, iOS and backend, Toni has a demonstrated knowledge of the information technology and services industry, with plenty of hands-on experience to back it up. He’s also an experienced Cloud engineer in Amazon Web Services (AWS), passionate about leveraging cloud technologies to improve the agility and efficiency of businesses. One of Toni’s most special traits is his talent for online shopping. In fact, our delivery guy is convinced that ‘Toni Vujević’ is a pseudonym for all DECODErs.

Related articles

6 surefire ways to motivate your development team

We'll discuss six surefire ways in which you can motivate your development team.

17 elements for designing a great mobile app 1

In this article, we will give you a brief overview of 17 mobile app design elements.

strizic

What a difference a ViewModel makes.

We’re a full-service partner to the world’s most ambitious companies — Let’s talk →

logo

You’ve made it this far. Let’s build your first application

DhiWise is free to get started with.

Image

Design to code

  • Figma plugin
  • Screen Library
  • Documentation
  • DhiWise University
  • DhiWise vs Anima
  • DhiWise vs Appsmith
  • DhiWise vs FlutterFlow
  • DhiWise vs Monday Hero
  • DhiWise vs Retool
  • DhiWise vs Supernova
  • DhiWise vs Amplication
  • DhiWise vs Bubble
  • DhiWise vs Figma Dev Mode
  • Terms of Service
  • Privacy Policy

github

The Fundamentals of Flutter Architecture: A Guide to the Presentation Layer

Authore Name

Kesar Bhimani

Authore Name

Nidhi Sorathiya

Detail Image

Flutter's popularity as a framework for building cross-platform applications is rising, and understanding its architecture is crucial for developers. The architecture of a Flutter app is designed to facilitate a clear separation of concerns, making the development process more manageable and the codebase more maintainable.

Exploring Flutter's Layered Architecture Components

Flutter app architecture is typically divided into several layers, each with a specific role in the application's overall functionality. The key layers include the presentation layer, business logic layer, and data layer. This layer focuses on the UI and how the app interacts with the user, while the business logic layer processes the user input and communicates with the data layer. The data layer handles data persistence, network calls, and other data processing tasks.

The Function of the Presentation Layer in Flutter Apps

The presentation layer in Flutter apps is where the visual aspects of the app come to life. It is responsible for rendering the UI components that users interact with and displaying the data in a user-friendly manner. This layer manages the state of the UI and reacts to user input, triggering state changes reflected in the UI.

Delving into the Presentation Layer

The presentation layer is a fundamental concept within the Flutter app architecture, serving as the visual foundation that users interact with. It is where the design meets the code, and the abstract ideas of the app's interface are translated into a concrete implementation that can be seen and interacted with on the screen.

The Build Method: Heart of the Presentation Layer

At the core of the presentation layer is the build method, which is called every time the framework needs to render the widgets on the screen. The build method is where developers define the part of the user interface that the widget represents, using a context to understand where the build process is taking place in the overall widget tree.

In this snippet, the build method returns a MaterialApp widget that contains a Scaffold. The Scaffold has an AppBar and a Center widget with a Text widget. This structure is a basic example of how the layer uses the build method to create the visual structure of a flutter app.

Managing State Changes within the Presentation Layer

State management is a critical aspect of this layer. When the state changes, the presentation layer must reflect these changes in the UI. Flutter uses the setState function to signal that the state of a widget has changed, prompting the framework to schedule a rebuild of the widget's UI.

In this example, the _onPressed function would contain the logic to update the state of the widget. When setState is called, it triggers the build method to run again with the updated state, ensuring that the UI represents the latest data.

Presentation Layer and User Input Handling

The presentation layer is not only about displaying content but also about handling user input. Widgets within the presentation layer are designed to be interactive, responding to user gestures and actions.

Here, a FloatingActionButton widget is used to handle user input. When the button is pressed, the _onPressed function is called, which typically contains logic to update the widget's state. This interaction between the presentation layer and user input is essential for creating a dynamic and responsive Flutter app.

Interplay Between Presentation and Data Layer

The architecture of a Flutter app is not just about individual layers but also about how these layers communicate and work together. The presentation layer and data layer have a symbiotic relationship, where data flows from the data layer and informs the presentation layer, which in turn can trigger updates back to the data layer based on user interactions.

Data Flow: From Data Layer to Presentation Layer

The data layer is the foundation that manages the app's data, including API calls, database interactions, and data processing. It serves as the source of truth for the app's data. The presentation layer, on the other hand, subscribes to changes in the data layer and updates the UI accordingly.

For example, a Flutter app might have a data layer that fetches user profiles from a network service:

The presentation layer would use this service to display the user profile:

In this example, the FutureBuilder widget handles the asynchronous operation of fetching the user profile. The presentation layer listens for the completion of the future and rebuilds the UI with the new data.

Presentation Layer’s Response to Data Layer Updates

When the data layer updates, the presentation layer must reflect these changes to provide the user with the most current information. This is typically achieved through various state management solutions that allow the presentation layer to rebuild its widgets when the underlying data changes.

For instance, if the user updates their profile, the data layer processes the new information, and the presentation layer must update the UI to show the latest profile details:

The presentation layer would then listen for these changes and update the UI:

Building a Concrete Implementation in Flutter

To illustrate the concepts discussed, we will build a concrete implementation in a Flutter app. This will involve creating a simple class with state property, understanding the widget build process, and finally, putting it together in an example showcasing a layered architecture.

Creating a Simple Class with State Property

In Flutter, a simple class that holds a state is often a StatefulWidget. This type of widget can rebuild its UI when its state changes. The state is typically held in a separate class that extends State.

In this SimpleCounter class, we have a state property count that keeps track of the number of times a button has been pressed. The increment method is used to update this count, and setState is called to trigger a rebuild of the widget.

Widget Build Process and BuildContext Context

The build method is where the UI is defined. It takes a BuildContext as an argument, which provides the context in which the build takes place. This context contains information about the widget's location in the widget tree.

Here, the build method returns a Scaffold with an AppBar, a Center widget displaying the count, and a FloatingActionButton that the user can press to increment the count.

Example: Implementing a Flutter App with Layered Architecture

Now, let's put it all together in an example that demonstrates a Flutter app with a layered architecture. We'll have a presentation layer that interacts with a data layer.

In this example, we have a CounterModel class representing the data layer. It holds the data and contains methods to manipulate it. The CounterScreen class represents the presentation layer. It subscribes to changes in the CounterModel and rebuilds its UI when the model's state changes.

Advanced Presentation Layer Techniques

To elevate the user experience of a Flutter app, developers can employ advanced techniques within the presentation layer. These methods focus on optimizing performance and enhancing the complexity and responsiveness of the user interface.

Optimizing the Build Method for Efficient State Changes

Efficiency in the build method is crucial for smooth state changes. To optimize the build method, developers should minimize the work done during each rebuild. This can be achieved by breaking down complex widgets into smaller, reusable components and using const constructors where possible.

In this code snippet, using const for Scaffold and its children means that if the build method is called again without any state changes affecting these widgets, Flutter will not rebuild them, thus saving resources.

Leveraging the Presentation Layer for Complex User Interfaces

The presentation layer can handle complex user interfaces by using custom widgets and animations. It can also manage various user interactions and transitions between different UI states.

This example shows how a complex UI might layer different widgets using a Stack to create a visually rich experience.

Example: Enhancing User Experience through the Presentation Layer

To enhance the user experience, the presentation layer can be designed to provide immediate feedback to user input, smooth animations, and transitions that guide the user through the app's flow.

In this example, AnimatedUserProfile could contain sophisticated animations that react to state changes, providing a fluid and engaging user experience.

In summary, the presentation layer is pivotal in the Flutter app architecture, acting as the bridge between the user and the application's logic and data. Developers can craft a responsive and intuitive user interface by understanding and utilizing the build method, managing state changes efficiently, and handling user input effectively. Advanced techniques within the presentation layer, such as optimizing widget rebuilds and incorporating complex UI elements, further enhance the user experience. With these concepts and practices in mind, developers are well-equipped to build high-performing and visually appealing Flutter apps that stand out in the competitive app market.

Flutter App Architecture: The Presentation Layer

Andrea Bizzotto

Andrea Bizzotto

Updated   Sep 21, 2023 11 min read

When writing Flutter apps, separating any business logic from the UI code is very important.

This makes our code more testable and easier to reason about , and is especially important as our apps become more complex.

To accomplish this, we can use design patterns to introduce a separation of concerns between different components in our app.

And for reference, we can adopt a layered app architecture such as the one represented in this diagram:

I have already covered some of the layers above in other articles:

  • Flutter App Architecture with Riverpod: An Introduction
  • Flutter App Architecture: The Repository Pattern
  • Flutter App Architecture: The Domain Model
  • Flutter App Architecture: The Application Layer

And this time, we will focus on the presentation layer and learn how we can use controllers to:

  • hold business logic
  • manage the widget state
  • interact with repositories in the data layer
This kind of controller is the same as the view model that you would use in the MVVM pattern . If you've worked with flutter_bloc before, it has the same role as a cubit .

We will learn about the AsyncNotifier class, which is a replacement for the StateNotifier and the ValueNotifier / ChangeNotifier classes in the Flutter SDK.

And to make this more useful, we will implement a simple authentication flow as an example.

Ready? Let's go!

A simple authentication flow

Let's consider a very simple app that we can use to sign in anonymously and toggle between two screens:

And in this article, we'll focus on how to implement:

  • an auth repository that we can use to sign in and sign out
  • a sign-in widget screen that we show to the user
  • the corresponding controller class that mediates between the two

Here's a simplified version of the reference architecture for this specific example:

You can find the complete source code for this app on GitHub . For more info about how it is organized, read this: Flutter Project Structure: Feature-first or Layer-first?

The AuthRepository class

As a starting point, we can define a simple abstract class that contains three methods that we'll use to sign in, sign out, and check the authentication state:

In practice, we also need a concrete class that implements AuthRepository . This could be based on Firebase or any other backend. We can even implement it with a fake repository for now. For more details, see this article about the repository pattern .

For completeness, we can also define a simple AppUser model class:

And if we use Riverpod, we also need a Provider that we can use to access our repository:

Next up, let's focus on the sign-in screen.

The SignInScreen widget

Suppose we have a simple SignInScreen widget defined like so:

This is just a simple Scaffold with an ElevatedButton in the middle.

Note that since this class extends ConsumerWidget , in the build() method we have an extra ref object that we can use to access providers as needed.

Accessing the AuthRepository directly from our widget

As a next step, we can use the onPressed callback to sign in like so:

This code works by obtaining the AuthRepository with a call to ref.read(authRepositoryProvider) . and calling the signInAnonymously() method on it.

This covers the happy path (sign-in successful). But we should also account for loading and error states by:

  • disabling the sign-in button and showing a loading indicator while sign-in is in progress
  • showing a SnackBar or alert if the call fails for any reason

The "StatefulWidget + setState" way

One simple way of addressing this is to:

  • convert our widget into a StatefulWidget (or rather, ConsumerStatefulWidget since we're using Riverpod)
  • add some local variables to keep track of state changes
  • set those variables inside calls to setState() to trigger a widget rebuild
  • use them to update the UI

Here's how the resulting code may look like:

For a simple app like this, this is probably ok.

But this approach gets quickly out of hand when we have more complex widgets, as we are mixing business logic and UI code in the same widget class.

And if we want to handle loading in error states consistently across multiple widgets, copy-pasting and tweaking the code above is quite error-prone (and not much fun).

Instead, it would be best to move all these concerns into a separate controller class that can:

  • mediate between our SignInScreen and the AuthRepository
  • provide a way for the widget to observe state changes and rebuild itself as a result

So let's see how to implement it in practice.

A controller class based on AsyncNotifier

The first step is to create a AsyncNotifier subclass which looks like this:

Or even better, we can use the new @riverpod syntax and let Riverpod Generator do the heavy lifting for us:

Either way, we need to implement a build method, which returns the initial value that should be used when the controller is first loaded.

If desired, we can use the build method to do some asynchronous initialization (such as loading some data from the network). But if the controller is "ready to go" as soon as it is created (just like in this case), we can leave the body empty and set the return type to Future<void> .

Implementing the method to sign in

Next up, let's add a method that we can use to sign in:

A few notes:

  • We obtain the authRepository by calling ref.read on the corresponding provider ( ref is a property of the base AsyncNotifier class)
  • Inside signInAnonymously() , we set the state to AsyncLoading so that the widget can show a loading UI
  • Then, we call AsyncValue.guard and await for the result (which will be either AsyncData or AsyncError )
AsyncValue.guard is a handy alternative to try / catch . For more info, read this: Use AsyncValue.guard rather than try/catch inside your StateNotifier subclasses

And as an extra tip, we can use a method tear-off to simplify our code even further:

This completes the implementation of our controller class, in just a few lines of code:

Note about the relationship between types

Note that there is a clear relationship between the return type of the build method and the type of the state property:

In fact, using AsyncValue<void> as the state allows us to represent three possible values:

  • default (not loading) as AsyncData (same as AsyncValue.data )
  • loading as AsyncLoading (same as AsyncValue.loading )
  • error as AsyncError (same as AsyncValue.error )
If you're not familiar with AsyncValue and its subclasses, read this: How to handle loading and error states with StateNotifier & AsyncValue in Flutter

Time to get back to our widget class and wire everything up!

Using our controller in the widget class

Here's an updated version of the SignInScreen that uses our new SignInScreenController class:

Note how in the build() method we watch our provider and rebuild the widget when the state changes.

And in the onPressed callback we read the provider's notifier and call signInAnonymously() . And we can also use the isLoading property to conditionally disable the button while sign-in is in progress.

We're almost done, and there's only one thing left to do.

Listening to state changes

Right at the top of the build method, we can add this:

We can use this code to call a listener callback whenever the state changes.

This is useful for showing an error alert or a SnackBar if an error occurs when signing in.

Bonus: An AsyncValue extension method

The listener code above is quite useful and we may want to reuse it in multiple widgets.

To do that, we can define this AsyncValue extension :

And then, in our widget, we can just import our extension and call this:

By implementing a custom controller class based on AsyncNotifier , we've separated our business logic from the UI code .

As a result, our widget class is now completely stateless and is only concerned with:

  • watching state changes and rebuilding as a result (with ref.watch )
  • responding to user input by calling methods in the controller (with ref.read )
  • listening to state changes and showing errors if something goes wrong (with ref.listen )

Meanwhile, the job of our controller is to:

  • talk to the repository on behalf of the widget
  • emit state changes as needed

And since the controller doesn't depend on any UI code, it can be easily unit tested , and this makes it an ideal place to store any widget-specific business logic.

In summary, widgets and controllers belong to the presentation layer in our app architecture:

But there are three additional layers: data , domain , and application , and you can learn about them here:

Or if you want to dive deeper, check out my Flutter Foundations course. 👇

Flutter Foundations Course Now Available

I launched a brand new course that covers Flutter app architecture in great depth, along with other important topics like state management, navigation & routing, testing, and much more:

Flutter Foundations Course

Flutter Foundations Course

Learn about State Management, App Architecture, Navigation, Testing, and much more by building a Flutter eCommerce app on iOS, Android, and web.

Invest in yourself with my high-quality Flutter courses.

Flutter & Firebase Masterclass

Flutter & Firebase Masterclass

Learn about Firebase Auth, Cloud Firestore, Cloud Functions, Stripe payments, and much more by building a full-stack eCommerce app with Flutter & Firebase.

The Complete Dart Developer Guide

The Complete Dart Developer Guide

Learn Dart Programming in depth. Includes: basic to advanced topics, exercises, and projects. Fully updated to Dart 2.15.

Flutter Animations Masterclass

Flutter Animations Masterclass

Master Flutter animations and build a completely custom habit tracking application.

ui presentation layer

Clean Architecture Guide (with tested examples): Data Flow != Dependency Rule

Mario Sanoguera de Lorenzo

Mario Sanoguera de Lorenzo

ProAndroidDev

Hello everyone! 👋 In this story I want to explain Clean Architecture (with tested examples) & talk about the most common mistake when adopting it (the difference between Data Flow and Dependency Rule).

This story is the follow up after my latest medium Intro to App Architecture. Make sure to check it out if you are interested in what makes a good Architecture & why + how to achieve a more maintainable codebase.

Let’s start explaining Data Flow in Clean Architecture with an example.

Imagine opening an app that loads a list of posts which contains additional user information. The Data Flow would be:

1. UI calls method from Presenter/ViewModel. 2. Presenter/ViewModel executes Use case. 3. Use case combines data from User and Post Repositories. 4. Each Repository returns data from a Data Source (Cached or Remote). 5. Information flows back to the UI where we display the list of posts.

From the example above we can see how the user action flows from the UI all the way up to the Data Source and then flows back down. This Data Flow is not the same flow as the Dependency Rule.

Dependency Rule

Dependency Rule is the relationship that exists between the different layers. Before explaining the Dependency Rule in Clean Architecture lets rotate the onion 90 degrees. This helps to point out layers & boundaries. 🆒

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 & Repository Interfaces. Use cases combine data from 1 or multiple Repository Interfaces.

Data Layer contains Repository Implementations and 1 or multiple Data Sources. Repositories are responsible to coordinate data from the different Data Sources. Data Layer depends on Domain Layer.

Explaining the Domain Layer

Domain (with business rules) is the most important Layer.

Domain is at the center of the onion which means it is the core of our program. This is one of the main reasons why it shouldn’t have any dependencies with other layers.

Presentation and Data Layers are less important since they are only implementations that can be easily replaced. The list of posts could be displayed in Android, iOS, Web or even Terminal if your code is properly decoupled. The same happens with a Database or any kind of Data Source, it can be easily switched.

The outer you go on the onion the most likely things are prone to change. One of the most common mistakes is to have your app driven by your data layer/specific data system. Making it hard to replace or bridge with different data sources down the line.

Domain Layer does NOT depend on Data Layer.

Having modules with the correct dependency rules means that our Domain doesn’t have any dependency on any other layer. Due to no dependencies to any Android Library the Domain Layer should be a Kotlin Module. This is an extra boundary that will prevent polluting our most valuable layer with framework related classes. It also promotes reusability across platforms in case we switch over the Framework as our Domain Layer is completely agnostic.

Explaining the Domain Layer with an example!

What is the real problem that we need to solve?

“Load a list of posts with some user information for each post”

This is the core of our solution no matter where the data comes from or how we present it. This belongs to a Use case inside our Domain Layer which is the most inner layer of the architecture (business logic).

For those who haven’t tried Clean Architecture yet Use cases will avoid God Presenters/ViewModels since the Presentation Layer will only execute Use cases and notify the view (Separation of concerns + Single Responsibility Principle). This will also improve the RUDT points ( R ead, U pdate, D ebug & T est) of your project.

Tests here (omitted to make the story shorter).

This Use case is combining data from 2 repositories (UserRepository & PostRepository).

How does Domain NOT depend on Data?

This is because Use cases in Domain are not using the actual implementation of the Repository that sits in the Data Layer. Instead, it is just using an abstraction/interface in the Domain Layer that acts as a contract for any repository who wants to provide the data.

In Clean Architecture it is the responsibility of the Data Layer to have 1 or multiple implementations of the Domain’s interfaces and to bind the interface with the actual implementation.

Dagger2 binding example:

Koin binding example:

This abstraction with the interface and its binding is the Dependency Inversion principle (D from SOLID) which is a way of decoupling modules.

High-level modules should not depend on low-level modules, both should depend on abstractions.

In simple terms, this means adding/depending on interfaces so we can easily switch the implementation and decouple our software modules.

Explaining the Data Layer: Repositories Implementation & Data Sources

The Repository Implementation implements the Domain Repository Interface and is in charge of combining 1 or multiple Data Sources. The most common ones are Memory, Cache & Remote.

This Repository is pulling from the cache and remote interfaces (each Data Source then binds to an implementation). This decoupling makes the Repository agnostic from its Data Sources, avoiding changes when switching a Data Source implementation.

Repositories expect from Data Sources the Domain Models already so it pushes the responsibility of mapping from Data to Domain to each individual Data Source implementation (or from Domain to Data in case you are pushing something to the Data Source).

Data Strategies.

Multiple Data Sources lead to different Data Strategies. My favorite is to only return Cache (unique source of truth) and to refresh Cache from Remote only when it is empty or there is a user action (swipe to refresh for ex.). This saves lots of data and was inspired after reading Build for the next billion users from Android Developers.

Final recap:

I’ve omitted the Presentation Layer as it only needs to execute use cases & display data. Remember that each layer has its own entities & mappers and that in order to keep our Domain Layer with no dependencies Data and Presentation are responsible to map to/from Domain Entities depending if you are pushing or pulling data.

Done! 👏 👏 👏

Sanogueralorenzo/android-kotlin-clean-architecture, android sample clean architecture app written in kotlin - sanogueralorenzo/android-kotlin-clean-architecture.

You can check my sample app that was used as an ex. by clicking up here ☝️

→ My friend Igor Wojda 👋🤖 ’s Clean Architecture slides and talk .

→ Issue asking why Domain isn’t depending on the Data layer.

Remember to follow, share & hit the 👏 button if you’ve liked it! (:

GitHub | LinkedIn | Twitter

Mario Sanoguera de Lorenzo

Written by Mario Sanoguera de Lorenzo

Staff Engineer @Tonal

More from Mario Sanoguera de Lorenzo and ProAndroidDev

Moshi with Retrofit in Kotlin ❤️

Moshi with Retrofit in Kotlin ❤️

Hello everyone 👋 today i want to show how to implement moshi with retrofit (new project or replacing gson) in an android project..

Seven recipes to understand flows and asynchrony in Kotlin

Seven recipes to understand flows and asynchrony in Kotlin

In the clean world of kotlin coroutines, we can have many tasks running at different times. suspend functions and flows are two examples....

Opinion: Jetpack Compose needs a Design System layer

Opinion: Jetpack Compose needs a Design System layer

Material design should be a choice, not the default..

ViewModel with Dagger2 (Android Architecture Components)

ViewModel with Dagger2 (Android Architecture Components)

Hello everyone 👋 in this story i want to share some light on how you can use viewmodel (android architecture components) with dagger 2…, recommended from medium.

Multi-Module with Clean Architecture

Syed Ovais Akhtar

Multi-Module with Clean Architecture

A multi-module app, in the context of software development, refers to an application that is structured and organized into multiple….

How does the recommended project structure for an Android app, built in Kotlin with MVVM…

Sujatha Mudadla

How does the recommended project structure for an Android app, built in Kotlin with MVVM…

Sure, let’s delve into the details of the typical android application project structure. the structure can vary slightly based on the….

ui presentation layer

Medium's Huge List of Publications Accepting Submissions

ui presentation layer

Staff Picks

The “Real” Repository Pattern in Android refers to an architectural approach that abstracts the…

The “Real” Repository Pattern in Android refers to an architectural approach that abstracts the…

Understanding the repository pattern.

A Deep Dive into Clean Architecture and Solid Principles

Amandeep Singh

A Deep Dive into Clean Architecture and Solid Principles

Building software for the future.

The Package by Feature approach

Vitor Britto

The Package by Feature approach

How it can help you build scalable and manageable projects..

A flexible, modern Android app architecture: complete step-by-step

A flexible, modern Android app architecture: complete step-by-step

Here we teach android architecture by example. that means showing *how* various architecture decisions are made. we will encounter….

Text to speech

  • Application Standards and Guidelines
  • UI Elements
  • Styles and Widgets
  • Getting Started

User Interface (Presentation Layer)

  • Middleware (Integration Layer)
  • Security - Implementation
  • Batch Processing
  • Email Handling
  • Testing and QA
  • Resources and Training
  • Build Server
  • Build Files
  • Batch Deployment
  • Ant Technology
  • Application Components
  • Platform Versioning
  • Platform Updates
  • Manifest Files
  • Shobboleth Guide
  • HOME  
  • Develop  

This section provides a list of how-to guides for the UXT UI stack. The stack consists of SpringMVC, SiteMesh, and jQuery.

How to use these guides

These guides will provide example solutions, sample code, or references to a list of UI technical problems most developers face when developing a web application here at ACT. Each guide will begin with a list of pre-requisite reading for the guide. Then it will provide solutions either via external resources or internal document.

Please keep in mind approaches taken by external tutorials are the easiest way for readers to learn. Some of these approaches, however, are not the recommend in a production environment here at ACT. So, use them as a learning tool, not the definite guide to building a web application.

The sample web application​ contains sample code demonstrated in these guides.  You can also see a live demo of the sample web application  on our QA server.

How to apply the same layout across all UC San Diego web applications?

  • Applying Decorators​

How to create a page?  How to link to a page?  How to get parameters when processing requests?

  • HTML Elements
  • Request Binding

How to build a form?  How to get parameters when processing forms?  How to validate user input?

  • Spring Form Taglib
  • HTML Form Elements
  • Form Binding
  • Double Submit
  • Form Binding Collections

How to create a different view such as a PDF?

How to send a email based on a template.

  • Sending an Email​​
  • Decorating a Page
  • Applying MVC
  • Creating a Page
  • Building a Form
  • Creating a View/Output
  • Terms & Conditions

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

rt68 profile image

Node.js Unscripted: The Behind-the-Scenes Saga of Tech's Most Dramatic Development

Ran Tu - Mar 26

itswillt profile image

⚛️ Explaining React's Types

Will T. - Mar 28

suzuki0430 profile image

Automating Looker Studio Data Updates with S3 CSVs Processed through BigQuery

Atsushi Suzuki - Mar 17

davidpincheira profile image

uso de @outputs en Angular

davidpincheira - Mar 8

DEV Community

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

ui presentation layer

A Primer on Layers: Understanding Layer-Based Architectures

Fernando Doglio

Fernando Doglio

Bits and Pieces

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

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

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

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

What are layers?

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

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

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

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

So we have 3 groups or layers:

  • 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.

How do layers affect your project?

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

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

You could have something like this:

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

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

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

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

Classic uses of layers in software architecture

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

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

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

Classic web application architecture: the MVC pattern

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

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

Put another way:

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

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

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

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

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

Creating your own pattern

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

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

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

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

However, we can see several improvement areas:

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

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

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

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

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

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

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

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

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

Build composable web applications

Don’t build web monoliths. Use Bit to create and compose decoupled software components — in your favorite frameworks like React or Node. Build scalable and modular applications with a powerful and enjoyable dev experience.

Bring your team to Bit Cloud to host and collaborate on components together, and greatly speed up, scale, and standardize development as a team. Start with composable frontends like a Design System or Micro Frontends, or explore the composable backend. Give it a try →

How We Build Micro Frontends

Building micro-frontends to speed up and scale our web development process..

blog.bitsrc.io

How we Build a Component Design System

Building a design system with components to standardize and scale our ui development process., the composable enterprise: a guide, to deliver in 2022, the modern enterprise must become composable., 7 tools for faster frontend development in 2022, tools you should know to build modern frontend applications faster, and have more fun..

Fernando Doglio

Written by Fernando Doglio

I write about technology, freelancing and more. Check out my FREE newsletter if you’re into Software Development: https://fernandodoglio.substack.com/

More from Fernando Doglio and Bits and Pieces

Understanding Peer Dependencies in JavaScript

Understanding Peer Dependencies in JavaScript

Peer dependencies are a must-know feature that many developers overlook.

Best-Practices for API Authorization

Chameera Dulanga

Best-Practices for API Authorization

4 best practices for api authorization.

Top 10 Microservice Anti-Patterns

Lahiru Hewawasam

Top 10 Microservice Anti-Patterns

Ten common anti-patterns and how to avoid them.

It’s 2024, you should be using React Server Components already

It’s 2024, you should be using React Server Components already

3 reasons why you should actually use rsc in all your projects, recommended from medium.

Micro-Frontend - Netflix Case Study

CodeParrot.ai

Micro-Frontend — Netflix Case Study

Implementing the API Gateway Pattern in a Microservices Based Application with Node.js

Ruvani Jayaweera

Implementing the API Gateway Pattern in a Microservices Based Application with Node.js

Build your own api gateway using node.js in under 5 minutes.

ui presentation layer

General Coding Knowledge

ui presentation layer

Stories to Help You Grow as a Software Developer

ui presentation layer

Coding & Development

ui presentation layer

William Stafford Parsons

Why I Charge a $100,000 Software Licensing Fee For 10 Lines of Code

I design and build new fundamental algorithms and data structures in computer science..

Exploring the Mediator Pattern and Its Role in the CQRS

Bhanuka Dissanayake

Level Up Coding

Exploring the Mediator Pattern and Its Role in the CQRS

Unlock the power of clean communication and scalable architecture in .net development through an exploration of the mediator pattern….

Logos of the internal Google framework Wiz and Angular. Under Wiz there’s a label “Performance critical (Google Search, Drive, etc.)” under Angular there’s a label “Highly interactive (Google Analytics, Google Cloud Console, etc.)“. There’s an arrow from Angular to Wiz and another from Wiz to Angular.

Angular Blog

Angular and Wiz Are Better Together

Authors: jatin ramanathan, minko gechev.

Advice From a Software Engineer With 8 Years of Experience

Benoit Ruiz

Better Programming

Advice From a Software Engineer With 8 Years of Experience

Practical tips for those who want to advance in their careers.

Text to speech

  • 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
  • Computer Network Tutorial

Basics of Computer Network

  • Basics of Computer Networking
  • Introduction to basic Networking Terminology
  • Goals of Networks
  • Basic characteristics of Computer Networks
  • Challenges of Computer Network
  • Physical Components of Computer Network

Network Hardware and Software

  • Types of Computer Networks
  • LAN Full Form
  • How to Set Up a LAN Network?
  • MAN Full Form in Computer Networking
  • MAN Full Form
  • WAN Full Form
  • Introduction of Internetworking
  • Difference between Internet, Intranet and Extranet
  • Protocol Hierarchies in Computer Network
  • Network Devices (Hub, Repeater, Bridge, Switch, Router, Gateways and Brouter)
  • Introduction of a Router
  • Introduction of Gateways
  • What is a network switch, and how does it work?

Network Topology

  • Types of Network Topology
  • Difference between Physical and Logical Topology
  • What is OSI Model? - Layers of OSI Model
  • Physical Layer in OSI Model
  • Data Link Layer
  • Session Layer in OSI model

Presentation Layer in OSI model

  • Application Layer in OSI Model
  • Protocol and Standard in Computer Networks
  • Examples of Data Link Layer Protocols
  • TCP/IP Model
  • TCP/IP Ports and Its Applications
  • What is Transmission Control Protocol (TCP)?
  • TCP 3-Way Handshake Process
  • Services and Segment structure in TCP
  • TCP Connection Establishment
  • TCP Connection Termination
  • Fast Recovery Technique For Loss Recovery in TCP
  • Difference Between OSI Model and TCP/IP Model

Medium Access Control

  • MAC Full Form
  • Channel Allocation Problem in Computer Network
  • Multiple Access Protocols in Computer Network
  • Carrier Sense Multiple Access (CSMA)
  • Collision Detection in CSMA/CD
  • Controlled Access Protocols in Computer Network

SLIDING WINDOW PROTOCOLS

  • Stop and Wait ARQ
  • Sliding Window Protocol | Set 3 (Selective Repeat)
  • Piggybacking in Computer Networks

IP Addressing

  • What is IPv4?
  • What is IPv6?
  • Introduction of Classful IP Addressing
  • Classless Addressing in IP Addressing
  • Classful Vs Classless Addressing
  • Classless Inter Domain Routing (CIDR)
  • Supernetting in Network Layer
  • Introduction To Subnetting
  • Difference between Subnetting and Supernetting
  • Types of Routing
  • Difference between Static and Dynamic Routing
  • Unicast Routing - Link State Routing
  • Distance Vector Routing (DVR) Protocol
  • Fixed and Flooding Routing algorithms
  • Introduction of Firewall in Computer Network

Congestion Control Algorithms

  • Congestion Control in Computer Networks
  • Congestion Control techniques in Computer Networks
  • Computer Network | Leaky bucket algorithm
  • TCP Congestion Control

Network Switching

  • Circuit Switching in Computer Network
  • Message switching techniques
  • Packet Switching and Delays in Computer Network
  • Differences Between Virtual Circuits and Datagram Networks

Application Layer:DNS

  • Domain Name System (DNS) in Application Layer
  • Details on DNS
  • Introduction to Electronic Mail
  • E-Mail Format
  • World Wide Web (WWW)
  • HTTP Full Form
  • Streaming Stored Video
  • What is a Content Distribution Network and how does it work?

CN Interview Quetions

  • Top 50 Networking Interview Questions (2024)
  • Top 50 TCP/IP interview questions and answers
  • Top 50 IP addressing interview questions and answers
  • Last Minute Notes - Computer Networks
  • Computer Network - Cheat Sheet
  • Network Layer
  • Transport Layer
  • Application Layer

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.

Please Login to comment...

Similar reads.

author

  • 10 Best Todoist Alternatives in 2024 (Free)
  • How to Get Spotify Premium Free Forever on iOS/Android
  • Yahoo Acquires Instagram Co-Founders' AI News Platform Artifact
  • OpenAI Introduces DALL-E Editor Interface
  • Top 10 R Project Ideas for Beginners in 2024

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

IMAGES

  1. Full Behance UX UI Presentation Template

    ui presentation layer

  2. Flutter App Architecture: The Presentation Layer

    ui presentation layer

  3. Free Behance UI UX Presentation Template XD

    ui presentation layer

  4. UI 레이어

    ui presentation layer

  5. presentation layer in 3 tier architecture

    ui presentation layer

  6. presentation layer in 3 tier architecture

    ui presentation layer

VIDEO

  1. What is Serverless Computing

  2. Arterial Pulse Signal Amplification by Adding a Uniform PDMS Layer to a Pyrex Based Micro fluidic Ta

  3. Application layer Presentation layer

  4. Lec- 7 Application Layer

  5. ux ui presentation

  6. presentation layer in computer network discuss

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. 3-Tier Architecture: Everything You Need to Know in a Nutshell

    Presentation Layer. Presentation Tier / Layer This is the top layer of the 3-tier architecture and represents the user interface (UI). It's the layer that end-users directly interact with, and it includes everything that the user experiences on their screen: menus, dialogs, display forms, and more.

  3. What Is Three-Tier Architecture?

    The presentation tier is the user interface and communication layer of the application, where the end user interacts with the application. Its main purpose is to display information to and collect information from the user. This top-level tier can run on a web browser, as desktop application, or a graphical user interface (GUI), for example.

  4. 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.

  5. 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 ...

  6. 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:

  7. User Interface Layer

    a. Presentation layer: The presentation layer is the user interface (UI) layer representing the website or application layout, including web pages, forms, and interactions of APIs. b. Business layer: The business layer contains the application's business logic, including the security, access, and authentication tasks.

  8. The mobile app architecture guide

    Presentation layer. The presentation layer, or front end, is the visible part of the app—the part that the user actually sees. As you can guess, the app's user interface (UI) is a big part of this layer. The main purpose of the presentation layer is to take the data sent by the business layer and display it in a way the user understands.

  9. What is the Presentation Layer, Anyway?

    It's the presentation layer that knows to put the right information into the appropriate fields of a customer record, for example: Name, Date of Birth, Address, etc. The presentation layer is where you'll find the code for making a program look nice as well. Most importantly to this discussion, the presentation layer is where RPA functions.

  10. Flutter Architecture: Understanding the Presentation Layer

    The presentation layer in Flutter apps is where the visual aspects of the app come to life. It is responsible for rendering the UI components that users interact with and displaying the data in a user-friendly manner. This layer manages the state of the UI and reacts to user input, triggering state changes reflected in the UI.

  11. Multitier architecture

    Multitier architecture. In software engineering, multitier architecture (often referred to as n-tier architecture) is a client-server architecture in which presentation, application processing and data management functions are physically separated. The most widespread use of multitier architecture is the three-tier architecture .

  12. Flutter App Architecture: The Presentation Layer

    Flutter App Architecture: The Domain Model. Flutter App Architecture: The Application Layer. And this time, we will focus on the presentation layer and learn how we can use controllers to: hold business logic. manage the widget state. interact with repositories in the data layer. This kind of controller is the same as the view model that you ...

  13. 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 ...

  14. 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 ...

  15. User Interface (Presentation Layer)

    These guides will provide example solutions, sample code, or references to a list of UI technical problems most developers face when developing a web application here at ACT. Each guide will begin with a list of pre-requisite reading for the guide. Then it will provide solutions either via external resources or internal document.

  16. 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

  17. 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, ...

  18. 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.

  19. 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.

  20. 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 ...

  21. Controller belongs to the Presentation layer?

    6. The controller controls the presentation layer logic. For all the business code, transactional use cases, persistence, etc., it typically delegates to a service layer. A typical way of doing that is to implement transactional services as spring beans and inject those spring beans in controllers.

  22. 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.

  23. Can I use Domain Objects directly in Presentation Layer

    1. Referencing other layers in the presentation. The presentation can reference other layers, this is a common practice because some layered architectures implement IoC and DI, but that is another topic. Even if the presentation references the other layers, that doesn't mean the presentation can directly access the domain layer.