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.

A Guide To 3-Tier Architecture

A Guid to 3-tier Architecture - Kens Learning Curve

A well-structured and organized solution is crucial for maintainability and scalability in software development. The 3-Tier architecture clarifies concerns, allowing developers to manage the application logic, data access, and presentation layers separately. In this article, we will explore the benefits of this architecture and learn how to implement it in a Visual Studio solution using C#. 

Different Architectures

There are many types of architectures you can use for your applications. You just have to find the one that suits your needs. I like the 3-tier architecture. It’s small, simple, and easy to create. But in some cases, I might change it because of my needs.

There are 9 known architectures we use these days in C#:

  • Monolithic architecture
  • Microservices architecture
  • 3-tier architecture
  • Model-View-Controller (MVC) architecture
  • Model-View-Presenter (MVP) architecture
  • Model-View-ViewModel (MVVM) architecture
  • Event-Driven architecture
  • Service-Oriented Architecture (SOA)
  • Client-Server architecture

I am not going to explain them all. It will become a very large page. But the top 3 popular architectures are:

  • Microservices architecture A way to break down a large and complex application into smaller, independent services that are connected. They communicate with each other through APIs. This architecture is becoming popular with bigger projects. You can maintain and deploy the smaller projects more easily.
  • 3-tier architecture This type of architecture separates an application into three logical components: the presentation layer, the application layer, and the data layer. This separation of concerns provides better scalability, maintainability, and ease of development.
  • Model-View-Controller (MVC) architecture  Well-known if you have created web applications and/or  APIs  with C#. It is a design that separates the application logic from the user interface. The Model component represents the data and the business logic, the View component displays the data, and the Controller component handles user input and updates the Model. This separation of concerns provides a more organized and maintainable codebase.

This tutorial explains the 3-tier architecture mainly because we use this one the most.

The 3-Tier Architecture

This architecture separates the application into three logical components. These three layers help to maintain the code and separation of concern. But for me, it has a different reason I use this architecture: reusability. 

Especially at a time when you might want to create a Windows, macOS, Android, Linux, and iOS app that does the same thing. Do you create the same class over and over again? No, you create a class library with the logic and reference that library in all the projects that need the logic. If something changes in the class library, all other projects get updated.

Three Different Layers

Each layer has its own responsibility but only talks to one other layer. The presentation layer only talks to the application layer and the application layer only talks to the data layer. That means that if you want to show a list of movies, for example, you need to ask the application layer which will ask the data layer. The application layer will send the information of the data layer to the presentation layer. The presentation layer never talks to the data layer directly.

The 3-tier architecture - A guide to 3-tier architecture - Kens Learning Curve

The Data Layer

The first layer I am discussing is the data layer. Maybe the name already tells you what this layer is about: Data. It could be data from a database or a file. Generally speaking, we use this layer to transport data from and to a data source.

This layer does not contain any form of logic. It just sends or retrieves data from the data source. Nothing special. Logic is placed in the application layer.

If you have multiple data sources you need to manage, you can create multiple data layers and bring them together in the application by using dependency injection.

The data layer is a layer that is disappearing a bit. Before we had ORMs, like  Entity Framework , we had to write a lot of code to retrieve and send data from and to a database. With Entity Framework, we don’t need that anymore. That is the reason the logic for the database is moving to the application layer.

The Application Layer

This layer is the beating heart for all your logic. Here you combine logic with the data from the data layer. This layer is responsible for calculations and decisions before sending the data to your presentation layer.

The application layer is often called the business layer. This is a small heritage from the time we had the DLL (data layer library) and the BLL (business layer library). In my projects, I usually call it the business.

For example, the presentation layer requests a list of movies, ordered by title. The application layer will retrieve all the movies from the data layer and sort them by title.

This layer does nothing with the data source directly. The reason is simple: The application layer should never know what kind of data source you use. If you implement dependency injection, the data source can change. Even the whole data layer can change (except for the interface). But the application layer should always be working without changing it.

You can have multiple application layers. I created a logger once. A simple logger that stores messages in a file. But later I needed a logger that stored the messages in a database. I didn’t want two loggers in the single class library representing my application layer. So I created a second application layer for the logger.

It’s usually this layer we  unit test  because it contains the most important code of our application.

The Presentation Layer

And last but not least; the presentation layer. This layer is what a user sees. It could be a console application, WinForms, or an API. It’s the one that gives output that a user or a client application can work with. This layer is also referred to as the top-most layer in this architecture.

It is responsible for presenting the data from the application layer in a user-friendly way. Examples of user-friendly are web pages, WinForms, and mobile apps.

A console application or a WinForms application has a clear GUI. You can click on stuff and it works. An API doesn’t have that. But it does expose JSON (or XML if you want). An API is considered a front-end application.

Conclusion On A Guide to 3-Tier Architecture

The 3-tier architecture is the most used because it’s easy to understand and implement. I encourage you to use this if you just start or create a small project. If you have a really, really small project; make your life easier, and don’t use layers.

The idea behind these layers is to separate data, logic, and application. I think the names are a bit confusing and most people think the application layer is the front end, but that’s the presentation layer. And that is why I call the application layer the business layer.

Related Articles

Learn C# Essential Concepts and Frameworks for New Developers - Kens Learning Curve

Learn C# Essentials and Frameworks for New Developers

Learn C# Part 9 Structure - Kens Learning Curve

Learn C# – Part 9: Basic Structure And A New Project

Kens Learning Curve

  • Kens Learning Curve

ChatGPT: Yay or nay?

10 reasons why you should unit test, you may also like, visual studio shortcuts, design patterns and design principles, to savechanges or not to savechanges, top 5 reasons to use c#, how to apply clean code with c#, the c# data types part 2 – int, the c# data types part 1 – string, the use of code comments.

Kens Learning Curve is all about learning C# and all that comes along with it. From short, practical tutorials to learning from A to Z.

All subjects are tried and used by myself and I don’t use ChatGPT to write the texts.

Useful links

  • Free Tutorials
  • C# Bootcamp

Use the contact form to contact me or send me an e-mail.

The contact form can be found here .

Email: [email protected]

@2023 – All Right Reserved. Designed and Developed by Kens Learning Curve

Stay up to date with news, deals, and much more!

  • Free C# Information Webinar
  • Online Courses
  • Kens Learning Paths
  • Technical Writer
  • Career Advise

Software Architecture Patterns by

Get full access to Software Architecture Patterns and 60K+ other titles, with a free 10-day trial of O'Reilly.

There are also live events, courses curated by job role, and more.

Chapter 1. Layered Architecture

The most common architecture pattern is the layered architecture pattern, otherwise known as the n-tier architecture pattern. This pattern is the de facto standard for most Java EE applications and therefore is widely known by most architects, designers, and developers. The layered architecture pattern closely matches the traditional IT communication and organizational structures found in most companies, making it a natural choice for most business application development efforts. 

Pattern Description

Components within the layered architecture pattern are organized into horizontal layers, each layer performing a specific role within the application (e.g., presentation logic or business logic). Although the layered architecture pattern does not specify the number and types of layers that must exist in the pattern, most layered architectures consist of four standard layers: presentation, business, persistence, and database ( Figure 1-1 ). In some cases, the business layer and persistence layer are combined into a single business layer, particularly when the persistence logic (e.g., SQL or HSQL) is embedded within the business layer components. Thus, smaller applications may have only three layers, whereas larger and more complex business applications may contain five or more layers. 

Each layer of the layered architecture pattern has a specific role and responsibility within the application. For example, a presentation layer would be responsible for handling all user interface and browser communication logic, whereas a business layer would be responsible for executing specific business rules associated with the request. Each layer in the architecture forms an abstraction around the work that needs to be done to satisfy a particular business request. For example, the presentation layer doesn’t need to know or worry about how to get customer data; it only needs to display that information on a screen in particular format. Similarly, the business layer doesn’t need to be concerned about how to format customer data for display on a screen or even where the customer data is coming from; it only needs to get the data from the persistence layer, perform business logic against the data (e.g., calculate values or aggregate data), and pass that information up to the presentation layer.  

Alt Text

Figure 1-1. Layered architecture pattern

One of the powerful features of the layered architecture pattern is the separation of concerns among components. Components within a specific layer deal only with logic that pertains to that layer. For example, components in the presentation layer deal only with presentation logic, whereas components residing in the business layer deal only with business logic. This type of component classification makes it easy to build effective roles and responsibility models into your architecture, and also makes it easy to develop, test, govern, and maintain applications using this architecture pattern due to well-defined component interfaces and limited component scope.

Key Concepts

Notice in Figure 1-2 that each of the layers in the architecture is marked as being  closed . This is a very important concept in the layered architecture pattern. A closed layer means that as a request moves from layer to layer, it must go through the layer right below it to get to the next layer below that one. For example, a request originating from the presentation layer must first go through the business layer and then to the persistence layer before finally hitting the database layer. 

Alt Text

Figure 1-2. Closed layers and request access

So why not allow the presentation layer direct access to either the persistence layer or database layer? After all, direct database access from the presentation layer is much faster than going through a bunch of unnecessary layers just to retrieve or save database information. The answer to this question lies in a key concept known as  layers of isolation . 

The layers of isolation concept means that changes made in one layer of the architecture generally don’t impact or affect components in other layers: the change is isolated to the components within that layer, and possibly another associated layer (such as a persistence layer containing SQL). If you allow the presentation layer direct access to the persistence layer, then changes made to SQL within the persistence layer would impact both the business layer and the presentation layer, thereby producing a very tightly coupled application with lots of interdependencies between components. This type of architecture then becomes very hard and expensive to change.  

The layers of isolation concept also means that each layer is independent of the other layers, thereby having little or no knowledge of the inner workings of other layers in the architecture. To understand the power and importance of this concept, consider a large refactoring effort to convert the presentation framework from JSP (Java Server Pages) to JSF (Java Server Faces). Assuming that the contracts (e.g., model) used between the presentation layer and the business layer remain the same, the business layer is not affected by the refactoring and remains completely independent of the type of user-interface framework used by the presentation layer.  

While closed layers facilitate layers of isolation and therefore help isolate change within the architecture, there are times when it makes sense for certain layers to be open. For example, suppose you want to add a shared-services layer to an architecture containing common service components accessed by components within the business layer (e.g., data and string utility classes or auditing and logging classes). Creating a services layer is usually a good idea in this case because architecturally it restricts access to the shared services to the business layer (and not the presentation layer). Without a separate layer, there is nothing architecturally that restricts the presentation layer from accessing these common services, making it difficult to govern this access restriction.  

In this example, the new services layer would likely reside  below  the business layer to indicate that components in this services layer are not accessible from the presentation layer. However, this presents a problem in that the business layer is now required to go through the services layer to get to the persistence layer, which makes no sense at all. This is an age-old problem with the layered architecture, and is solved by creating open layers within the architecture.  

As illustrated in Figure 1-3 , the services layer in this case is marked as open,  meaning requests are allowed to bypass this open layer and go directly to the layer below it. In the following example, since the services layer is open, the business layer is now allowed to bypass it and go directly to the persistence layer, which makes perfect sense.  

Alt Text

Figure 1-3. Open layers and request flow

Leveraging the concept of open and closed layers helps define the relationship between architecture layers and request flows and also provides designers and developers with the necessary information to understand the various layer access restrictions within the architecture. Failure to document or properly communicate which layers in the architecture are open and closed (and why) usually results in tightly coupled and brittle architectures that are very difficult to test, maintain, and deploy.

Pattern Example

To illustrate how the layered architecture works, consider a request from a business user to retrieve customer information for a particular individual as illustrated in Figure 1-4 . The black arrows show the request flowing down to the database to retrieve the customer data, and the red arrows show the response flowing back up to the screen to display the data. In this example, the customer information consists of both customer data and order data (orders placed by the customer).  

The customer screen is responsible for accepting the request and displaying the customer information. It does not know where the data is, how it is retrieved, or how many database tables must be queries to get the data. Once the customer screen receives a request to get customer information for a particular individual, it then forwards that request onto the customer delegate module. This module is responsible for knowing which modules in the business layer can process that request and also how to get to that module and what data it needs (the contract). The customer object in the business layer is responsible for aggregating all of the information needed by the business request (in this case to get customer information). This module calls out to the  customer dao  (data access object) module in the persistence layer to get customer data, and also the order dao module to get order information. These modules in turn execute SQL statements to retrieve the corresponding data and pass it back up to the customer object in the business layer. Once the customer object receives the data, it aggregates the data and passes that information back up to the customer delegate, which then passes that data to the customer screen to be presented to the user.      

Alt Text

Figure 1-4. Layered architecture example

From a technology perspective, there are literally dozens of ways these modules can be implemented. For example, in the Java platform, the customer screen can be a (JSF) Java Server Faces screen coupled with the customer delegate as the managed bean component. The customer object in the business layer can be a local Spring bean or a remote EJB3 bean. The data access objects illustrated in the previous example can be implemented as simple POJO’s (Plain Old Java Objects), MyBatis XML Mapper files, or even objects encapsulating raw JDBC calls or Hibernate queries. From a Microsoft platform perspective, the customer screen can be an ASP (active server pages) module using the .NET framework to access C# modules in the business layer, with the customer and order data access modules implemented as ADO (ActiveX Data Objects). 

Considerations

The layered architecture pattern is a solid general-purpose pattern, making it a good starting point for most applications, particularly when you are not sure what architecture pattern is best suited for your application. However, there are a couple of things to consider from an architecture standpoint when choosing this pattern.

The first thing to watch out for is what is known as the architecture sinkhole anti-pattern . This anti-pattern describes the situation where requests flow through multiple layers of the architecture as simple pass-through processing with little or no logic performed within each layer. For example, assume the presentation layer responds to a request from the user to retrieve customer data. The presentation layer passes the request to the business layer, which simply passes the request to the persistence layer, which then makes a simple SQL call to the database layer to retrieve the customer data. The data is then passed all the way back up the stack with no additional processing or logic to aggregate, calculate, or transform the data. 

Every layered architecture will have at least some scenarios that fall into the architecture sinkhole anti-pattern. The key, however, is to analyze the percentage of requests that fall into this category. The 80-20 rule is usually a good practice to follow to determine whether or not you are experiencing the architecture sinkhole anti-pattern. It is typical to have around 20 percent of the requests as simple pass-through processing and 80 percent of the requests having some business logic associated with the request. However, if you find that this ratio is reversed and a majority of your requests are simple pass-through processing, you might want to consider making some of the architecture layers open, keeping in mind that it will be more difficult to control change due to the lack of layer isolation. 

Another consideration with the layered architecture pattern is that it tends to lend itself toward monolithic applications, even if you split the presentation layer and business layers into separate deployable units. While this may not be a concern for some applications, it does pose some potential issues in terms of deployment, general robustness and reliability, performance, and scalability.   

Pattern Analysis

The following table contains a rating and analysis of the common architecture characteristics for the layered architecture pattern. The rating for each characteristic is based on the natural tendency for that characteristic as a capability based on a typical implementation of the pattern, as well as what the pattern is generally known for. For a side-by-side comparison of how this pattern relates to other patterns in this report, please refer to  Appendix A  at the end of this report.

Get Software Architecture Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.

Don’t leave empty-handed

Get Mark Richards’s Software Architecture Patterns ebook to better understand how to design components—and how they should interact.

It’s yours, free.

Cover of Software Architecture Patterns

Check it out now on O’Reilly

Dive in for free with a 10-day trial of the O’Reilly learning platform—then explore all the other resources our members count on to build skills and solve problems every day.

presentation business data layer

Presentation Domain Data Layering

26 August 2015

Martin Fowler

team organization

encapsulation

application architecture

web development

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Further Reading

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

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

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

Acknowledgements

presentation business data layer

3 Layered Architecture

Introduction.

Here in this article, I would like to cover the typical three layer architecture in C# .NET. It is a very useful approach for coding due to easy code maintenance.

First let me give you a small overview about the topic I would like to cover in this article.

  • Tier vs. Layer
  • Three Tier/Layer Architecture Design Components
  • Demo: Three Layer Windows Application in C#.NET

1. Tier vs. Layer

1.1 Tier: Tier indicates a physical separation of components, which may mean different assemblies such as DLL, EXE, etc. on the same server or multiple servers.

img0

As you can see in the above figure, Data Tier have no direction with Presentation Tier, but there is an intermediate Tier called Business Tier which is mainly responsible to pass the data from Data Tier to Presentation Tier and to add defined business logic to Data.

So, if we separate each Tier by its functionality, then we come to know the below conclusion:

img1

1.2 Layer: Layer indicates logical separation of components, such as having distinct namespaces and classes for the Database Access Layer, Business Logic Layer and User Interface Layer.

img2

2. Three Tier/Layer Architecture Design Components

As we have already seen, tier is the sum of all the physical components. We can separate the three tiers as Data Tier, Business Tier and Presentation Tier.

img4

  • Data Tier is basically the server which stores all the application’s data. Data tier contents Database Tables, XML Files and other means of storing Application Data.
  • Business Tier is mainly working as the bridge between Data Tier and Presentation Tier. All the Data passes through the Business Tier before passing to the presentation Tier. Business Tier is the sum of Business Logic Layer, Data Access Layer and Value Object and other components used to add business logic.
  • Presentation Tier is the tier in which the users interact with an application. Presentation Tier contents Shared UI code, Code Behind and Designers used to represent information to user.

img3

The above figure is a mixture of Three Tier and Three Layer Architecture. Here, we can clearly see a different between Tier and Layer. Since each component is independent of each other, they are easily maintainable without changing the whole code.

This approach is really very important when several developers are working on the same project and some module needs to be re-used in another project. In a way, we can distribute work among developers and also maintain it in the future without much problems.

Testing is also a very important issue for Architecture when we are considering writing a test case for the project. Since it’s like a modular architecture, it’s very handy testing each module and to trace out bugs without going through the entire code.

3 . Demo: 3 Layer Windows Application in C#.NET

img6

Let’s go though from one module to other to have a better understanding of it.

dbConnection

This class is mainly used to do the database activity like Select, Update and Delete query to database. It also checks if the database connection is open or not. If database connection is not open, then it opens the connection and performs the database query. The database results are to be received and being passing in Data Table in this class.

This class takes the database setting from the app.config file so it’s really flexible to manage the database settings.

Database Access Layer

Database Access Layer (DAO) builds the query based on received parameters from the Business Logic Layer and passes it the   dbConnection   class for execution. And simple return results from the   dbConnection   class to Business Logic Layer.

Value Object

Value Object is nothing more but a class with the contents   GET   and   SET   methods. It’s mainly used to pass Data from one class to another. It’s directly connected with Business Logic Layer and Presentation Layer. As you can see in the diagram object values are being SET in Business Logic Layer and GET from Presentation Layer.

Business Logic Layer

Business Logic Layer (BUS) works as a bridge between Presentation Layer and DAO. All the user values received from the presentation layer are being passed to BUS. The results received from the DAO are in row data in Data Table format but in BUS it’s converting into Value Objects (VO). Business Logic Layer (BUS) is the most important class in the whole architecture because it mainly contains all the business logic of the program. Whenever a user wants to update the business logic of the program only need to update this class.

Presentation Layer

Presentation Layer is the only layer which is directly connected with the user. So in this matter, it’s also a really important layer for marketing purposes. Presentation Layer is mainly used for getting user data and then passing it to Business Logic Layer for further procedure, and when data is received in Value Object then it’s responsible to represent value object in the appropriate form which user can understand.

Hope this artilce helps beginners in understanding the three layered architecture.

Leave a reply cancel reply.

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

With Canarys, Let’s Plan. Grow. Strive. Succeed.

Copyright © 2024 Canarys Automations Limited . All Rights Reserved.

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

Presentation Layer in OSI model

Prerequisite : OSI Model

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

Functions of Presentation Layer :

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

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

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

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

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

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

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

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

author

Please Login to comment...

Similar reads.

  • California Lawmakers Pass Bill to Limit AI Replicas
  • Best 10 IPTV Service Providers in Germany
  • Python 3.13 Releases | Enhanced REPL for Developers
  • IPTV Anbieter in Deutschland - Top IPTV Anbieter Abonnements
  • Content Improvement League 2024: From Good To A Great Article

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Creating a Business Logic Layer (C#)

  • 9 contributors

by Scott Mitchell

Download PDF

In this tutorial we'll see how to centralize your business rules into a Business Logic Layer (BLL) that serves as an intermediary for data exchange between the presentation layer and the DAL.

Introduction

The Data Access Layer (DAL) created in the first tutorial cleanly separates the data access logic from the presentation logic. However, while the DAL cleanly separates the data access details from the presentation layer, it does not enforce any business rules that may apply. For example, for our application we may want to disallow the CategoryID or SupplierID fields of the Products table to be modified when the Discontinued field is set to 1, or we might want to enforce seniority rules, prohibiting situations in which an employee is managed by someone who was hired after them. Another common scenario is authorization perhaps only users in a particular role can delete products or can change the UnitPrice value.

In this tutorial we'll see how to centralize these business rules into a Business Logic Layer (BLL) that serves as an intermediary for data exchange between the presentation layer and the DAL. In a real-world application, the BLL should be implemented as a separate Class Library project; however, for these tutorials we'll implement the BLL as a series of classes in our App_Code folder in order to simplify the project structure. Figure 1 illustrates the architectural relationships among the presentation layer, BLL, and DAL.

The BLL Separates the Presentation Layer from the Data Access Layer and Imposes Business Rules

Figure 1 : The BLL Separates the Presentation Layer from the Data Access Layer and Imposes Business Rules

Step 1: Creating the BLL Classes

Our BLL will be composed of four classes, one for each TableAdapter in the DAL; each of these BLL classes will have methods for retrieving, inserting, updating, and deleting from the respective TableAdapter in the DAL, applying the appropriate business rules.

To more cleanly separate the DAL- and BLL-related classes, let's create two subfolders in the App_Code folder, DAL and BLL . Simply right-click on the App_Code folder in the Solution Explorer and choose New Folder. After creating these two folders, move the Typed DataSet created in the first tutorial into the DAL subfolder.

Next, create the four BLL class files in the BLL subfolder. To accomplish this, right-click on the BLL subfolder, choose Add a New Item, and choose the Class template. Name the four classes ProductsBLL , CategoriesBLL , SuppliersBLL , and EmployeesBLL .

Add Four New Classes to the App_Code Folder

Figure 2 : Add Four New Classes to the App_Code Folder

Next, let's add methods to each of the classes to simply wrap the methods defined for the TableAdapters from the first tutorial. For now, these methods will just call directly into the DAL; we'll return later to add any needed business logic.

If you are using Visual Studio Standard Edition or above (that is, you're not using Visual Web Developer), you can optionally design your classes visually using the Class Designer . Refer to the Class Designer Blog for more information on this new feature in Visual Studio.

For the ProductsBLL class we need to add a total of seven methods:

  • GetProducts() returns all products
  • GetProductByProductID(productID) returns the product with the specified product ID
  • GetProductsByCategoryID(categoryID) returns all products from the specified category
  • GetProductsBySupplier(supplierID) returns all products from the specified supplier
  • AddProduct(productName, supplierID, categoryID, quantityPerUnit, unitPrice, unitsInStock, unitsOnOrder, reorderLevel, discontinued) inserts a new product into the database using the values passed-in; returns the ProductID value of the newly inserted record
  • UpdateProduct(productName, supplierID, categoryID, quantityPerUnit, unitPrice, unitsInStock, unitsOnOrder, reorderLevel, discontinued, productID) updates an existing product in the database using the passed-in values; returns true if precisely one row was updated, false otherwise
  • DeleteProduct(productID) deletes the specified product from the database

ProductsBLL.cs

The methods that simply return data GetProducts , GetProductByProductID , GetProductsByCategoryID , and GetProductBySuppliersID are fairly straightforward as they simply call down into the DAL. While in some scenarios there may be business rules that need to be implemented at this level (such as authorization rules based on the currently logged on user or the role to which the user belongs), we'll simply leave these methods as-is. For these methods, then, the BLL serves merely as a proxy through which the presentation layer accesses the underlying data from the Data Access Layer.

The AddProduct and UpdateProduct methods both take in as parameters the values for the various product fields and add a new product or update an existing one, respectively. Since many of the Product table's columns can accept NULL values ( CategoryID , SupplierID , and UnitPrice , to name a few), those input parameters for AddProduct and UpdateProduct that map to such columns use nullable types . Nullable types are new to .NET 2.0 and provide a technique for indicating whether a value type should, instead, be null . In C# you can flag a value type as a nullable type by adding ? after the type (like int? x; ). Refer to the Nullable Types section in the C# Programming Guide for more information.

All three methods return a Boolean value indicating whether a row was inserted, updated, or deleted since the operation may not result in an affected row. For example, if the page developer calls DeleteProduct passing in a ProductID for a non-existent product, the DELETE statement issued to the database will have no affect and therefore the DeleteProduct method will return false .

Note that when adding a new product or updating an existing one we take in the new or modified product's field values as a list of scalars as opposed to accepting a ProductsRow instance. This approach was chosen because the ProductsRow class derives from the ADO.NET DataRow class, which doesn't have a default parameterless constructor. In order to create a new ProductsRow instance, we must first create a ProductsDataTable instance and then invoke its NewProductRow() method (which we do in AddProduct ). This shortcoming rears its head when we turn to inserting and updating products using the ObjectDataSource. In short, the ObjectDataSource will try to create an instance of the input parameters. If the BLL method expects a ProductsRow instance, the ObjectDataSource will try to create one, but fail due to the lack of a default parameterless constructor. For more information on this problem, refer to the following two ASP.NET Forums posts: Updating ObjectDataSources with Strongly-Typed DataSets , and Problem With ObjectDataSource and Strongly-Typed DataSet .

Next, in both AddProduct and UpdateProduct , the code creates a ProductsRow instance and populates it with the values just passed in. When assigning values to DataColumns of a DataRow various field-level validation checks can occur. Therefore, manually putting the passed in values back into a DataRow helps ensure the validity of the data being passed to the BLL method. Unfortunately the strongly-typed DataRow classes generated by Visual Studio do not use nullable types. Rather, to indicate that a particular DataColumn in a DataRow should correspond to a NULL database value we must use the SetColumnNameNull() method.

In UpdateProduct we first load in the product to update using GetProductByProductID(productID) . While this may seem like an unnecessary trip to the database, this extra trip will prove worthwhile in future tutorials that explore optimistic concurrency. Optimistic concurrency is a technique to ensure that two users who are simultaneously working on the same data don't accidentally overwrite one another's changes. Grabbing the entire record also makes it easier to create update methods in the BLL that only modify a subset of the DataRow's columns. When we explore the SuppliersBLL class we'll see such an example.

Finally, note that the ProductsBLL class has the DataObject attribute applied to it (the [System.ComponentModel.DataObject] syntax right before the class statement near the top of the file) and the methods have DataObjectMethodAttribute attributes . The DataObject attribute marks the class as being an object suitable for binding to an ObjectDataSource control , whereas the DataObjectMethodAttribute indicates the purpose of the method. As we'll see in future tutorials, ASP.NET 2.0's ObjectDataSource makes it easy to declaratively access data from a class. To help filter the list of possible classes to bind to in the ObjectDataSource's wizard, by default only those classes marked as DataObjects are shown in the wizard's drop-down list. The ProductsBLL class will work just as well without these attributes, but adding them makes it easier to work with in the ObjectDataSource's wizard.

Adding the Other Classes

With the ProductsBLL class complete, we still need to add the classes for working with categories, suppliers, and employees. Take a moment to create the following classes and methods using the concepts from the example above:

CategoriesBLL.cs

  • GetCategories()
  • GetCategoryByCategoryID(categoryID)

SuppliersBLL.cs

  • GetSuppliers()
  • GetSupplierBySupplierID(supplierID)
  • GetSuppliersByCountry(country)
  • UpdateSupplierAddress(supplierID, address, city, country)

EmployeesBLL.cs

  • GetEmployees()
  • GetEmployeeByEmployeeID(employeeID)
  • GetEmployeesByManager(managerID)

The one method worth noting is the SuppliersBLL class's UpdateSupplierAddress method. This method provides an interface for updating just the supplier's address information. Internally, this method reads in the SupplierDataRow object for the specified supplierID (using GetSupplierBySupplierID ), sets its address-related properties, and then calls down into the SupplierDataTable 's Update method. The UpdateSupplierAddress method follows:

Refer to this article's download for my complete implementation of the BLL classes.

Step 2: Accessing the Typed DataSets Through the BLL Classes

In the first tutorial we saw examples of working directly with the Typed DataSet programmatically, but with the addition of our BLL classes, the presentation tier should work against the BLL instead. In the AllProducts.aspx example from the first tutorial, the ProductsTableAdapter was used to bind the list of products to a GridView, as shown in the following code:

To use the new BLL classes, all that needs to be changed is the first line of code simply replace the ProductsTableAdapter object with a ProductBLL object:

The BLL classes can also be accessed declaratively (as can the Typed DataSet) by using the ObjectDataSource. We'll be discussing the ObjectDataSource in greater detail in the following tutorials.

The List of Products is Displayed in a GridView

Figure 3 : The List of Products is Displayed in a GridView ( Click to view full-size image )

Step 3: Adding Field-Level Validation to the DataRow Classes

Field-level validation are checks that pertains to the property values of the business objects when inserting or updating. Some field-level validation rules for products include:

  • The ProductName field must be 40 characters or less in length
  • The QuantityPerUnit field must be 20 characters or less in length
  • The ProductID , ProductName , and Discontinued fields are required, but all other fields are optional
  • The UnitPrice , UnitsInStock , UnitsOnOrder , and ReorderLevel fields must be greater than or equal to zero

These rules can and should be expressed at the database level. The character limit on the ProductName and QuantityPerUnit fields are captured by the data types of those columns in the Products table ( nvarchar(40) and nvarchar(20) , respectively). Whether fields are required and optional are expressed by if the database table column allows NULL s. Four check constraints exist that ensure that only values greater than or equal to zero can make it into the UnitPrice , UnitsInStock , UnitsOnOrder , or ReorderLevel columns.

In addition to enforcing these rules at the database they should also be enforced at the DataSet level. In fact, the field length and whether a value is required or optional are already captured for each DataTable's set of DataColumns. To see the existing field-level validation automatically provided, go to the DataSet Designer, select a field from one of the DataTables and then go to the Properties window. As Figure 4 shows, the QuantityPerUnit DataColumn in the ProductsDataTable has a maximum length of 20 characters and does allow NULL values. If we attempt to set the ProductsDataRow 's QuantityPerUnit property to a string value longer than 20 characters an ArgumentException will be thrown.

The DataColumn Provides Basic Field-Level Validation

Figure 4 : The DataColumn Provides Basic Field-Level Validation ( Click to view full-size image )

Unfortunately, we can't specify bounds checks, such as the UnitPrice value must be greater than or equal to zero, through the Properties window. In order to provide this type of field-level validation we need to create an event handler for the DataTable's ColumnChanging event. As mentioned in the preceding tutorial , the DataSet, DataTables, and DataRow objects created by the Typed DataSet can be extended through the use of partial classes. Using this technique we can create a ColumnChanging event handler for the ProductsDataTable class. Start by creating a class in the App_Code folder named ProductsDataTable.ColumnChanging.cs .

Add a New Class to the App_Code Folder

Figure 5 : Add a New Class to the App_Code Folder ( Click to view full-size image )

Next, create an event handler for the ColumnChanging event that ensures that the UnitPrice , UnitsInStock , UnitsOnOrder , and ReorderLevel column values (if not NULL ) are greater than or equal to zero. If any such column is out of range, throw an ArgumentException .

ProductsDataTable.ColumnChanging.cs

Step 4: Adding Custom Business Rules to the BLL's Classes

In addition to field-level validation, there may be high-level custom business rules that involve different entities or concepts not expressible at the single column level, such as:

  • If a product is discontinued, its UnitPrice cannot be updated
  • An employee's country of residence must be the same as their manager's country of residence
  • A product cannot be discontinued if it is the only product provided by the supplier

The BLL classes should contain checks to ensure adherence to the application's business rules. These checks can be added directly to the methods to which they apply.

Imagine that our business rules dictate that a product could not be marked discontinued if it was the only product from a given supplier. That is, if product X was the only product we purchased from supplier Y , we could not mark X as discontinued; if, however, supplier Y supplied us with three products, A , B , and C , then we could mark any and all of these as discontinued. An odd business rule, but business rules and common sense aren't always aligned!

To enforce this business rule in the UpdateProducts method we'd start by checking if Discontinued was set to true and, if so, we'd call GetProductsBySupplierID to determine how many products we purchased from this product's supplier. If only one product is purchased from this supplier, we throw an ApplicationException .

Responding to Validation Errors in the Presentation Tier

When calling the BLL from the presentation tier we can decide whether to attempt to handle any exceptions that might be raised or let them bubble up to ASP.NET (which will raise the HttpApplication 's Error event). To handle an exception when working with the BLL programmatically, we can use a try...catch block, as the following example shows:

As we'll see in future tutorials, handling exceptions that bubble up from the BLL when using a data Web control for inserting, updating, or deleting data can be handled directly in an event handler as opposed to having to wrap code in try...catch blocks.

A well architected application is crafted into distinct layers, each of which encapsulates a particular role. In the first tutorial of this article series we created a Data Access Layer using Typed DataSets; in this tutorial we built a Business Logic Layer as a series of classes in our application's App_Code folder that call down into our DAL. The BLL implements the field-level and business-level logic for our application. In addition to creating a separate BLL, as we did in this tutorial, another option is to extend the TableAdapters' methods through the use of partial classes. However, using this technique does not allow us to override existing methods nor does it separate our DAL and our BLL as cleanly as the approach we've taken in this article.

With the DAL and BLL complete, we're ready to start on our presentation layer. In the next tutorial we'll take a brief detour from data access topics and define a consistent page layout for use throughout the tutorials.

Happy Programming!

About the Author

Scott Mitchell, author of seven ASP/ASP.NET books and founder of 4GuysFromRolla.com , has been working with Microsoft Web technologies since 1998. Scott works as an independent consultant, trainer, and writer. His latest book is Sams Teach Yourself ASP.NET 2.0 in 24 Hours . He can be reached at [email protected]. or via his blog, which can be found at http://ScottOnWriting.NET .

Special Thanks To

This tutorial series was reviewed by many helpful reviewers. Lead reviewers for this tutorial were Liz Shulok, Dennis Patterson, Carlos Santos, and Hilton Giesenow. Interested in reviewing my upcoming MSDN articles? If so, drop me a line at [email protected].

Previous Next

Was this page helpful?

Additional resources

Register for Simple Talk

Get the latest Opinion, Podcasts, Webinars, and Events, delivered straight to your inbox.

.NET Application Architecture: the Data Access Layer

Damon Armstrong

Share to social media

presentation business data layer

Designing and building a robust data access layer

Building an understanding of architectural concepts is an essential aspect of managing your career. Technical interviews normally contain a battery of questions to gauge your architectural knowledge during the hiring process, and your architectural ability only becomes more important as you ascend through the ranks. So it’s always a good idea to make sure you have a good grasp on the fundamentals. In this article you will explore a key component of application architecture known as the Data Access Layer (DAL), which helps separate data-access logic from your business objects. The article discusses the concepts behind the DAL, and the associated PDF file takes a look at a full-blown DAL implementation. This is the first in a series of articles discussing some of the cool things you can do with a DAL, so the code and concepts in this article form the base for future discussions.

Layered design and the data access layer

Layered application designs are extremely popular because they increase application performance, scalability, flexibility, code reuse, and have a myriad of other benefits that I could rattle off if I had all of the architectural buzzwords memorized. In the classic three tier design, applications break down into three major areas of functionality:

  • The data layer manages the physical storage and retrieval of data
  • The business layer maintains business rules and logic
  • The presentation layer houses the user interface and related presentation code.

Inside each of these tiers there may also exist a series of sub-layers that provide an even more granular break up the functional areas of the application. Figure 1 outlines a basic three tired architecture in ASP.NET along with some of the sub-tiers that you may encounter:

253-DAL001.jpg

Figure 1 – Three tiered ASP.NET application with sub-tiers

The presentation tier

In the presentation layer, the code-behind mechanism for ASP.NET pages and user controls is a prominent example of a layered design. The markup file defines the look and layout of the web form and the code behind file contains the presentation logic. It’s a clean separation because both the markup and the code-behind layers house specific sets of functionality that benefit from being apart. Designers don’t have to worry about messing up code to make user interface changes, and developers don’t have to worry about sifting through the user-interface to update code.

The data tier

You also see sub-layers in the data tier with database systems. Tables define the physical storage of data in a database, but stored procedures and views allow you to manipulate data as it goes into and out of those tables. Say, for example, you need to denormalize a table and therefore have to change its physical storage structure. If you access tables directly in the business layer, then you are forced to update your business tier to account for the changes to the table. If you use a layer of stored procedures and views to access the data, then you can expose the same logical structure by updating a view or stored procedure to account for the physical change without having to touch any code in your business layer. When used appropriately, a layered design can lessen the overall impact of changes to the application.

The business tier

And of course, this brings us to the topic of business objects and the Data Access Layer (also known as the DAL), two sub-layers within the business tier. A business object is a component that encapsulates the data and business processing logic for a particular business entity. It is not, however, a persistent storage mechanism. Since business objects cannot store data indefinitely, the business tier relies on the data tier for long term data storage and retrieval. Thus, your business tier contains logic for retrieving persistent data from the data-tier and placing it into business objects and, conversely, logic that persists data from business objects into the data tier. This is called data access logic.

Some developers choose to put the data access logic for their business objects directly in the business objects themselves, tightly binding the two together. This may seem like a logical choice at first because from the business object perspective it seems to keep everything nicely packaged. You will begin noticing problems, however, if you ever need to support multiple databases, change databases, or even overhaul your current database significantly. Let’s say, for example, that your boss comes to you and says that you will be moving your application’s database from Oracle to SQL Server and that you have four months to do it. In the meantime, however, you have to continue supporting whatever business logic changes come up. Your only real option is to make a complete copy of the business object code so you can update the data access logic in it to support SQL Server. As business object changes arise, you have to make those changes to both the SQL Server code base and the Oracle code base. Not fun. Figure 2 depicts this scenario:

253-DAL002.jpg

Figure 2 – Business objects with embedded data access logic

A more flexible option involves removing the data access logic from the business objects and placing it all in a separate assembly known as the DAL. This gives you a clean separation between your business objects and the data access logic used to populate those business objects. Presented with the same challenge of making the switch from Oracle to SQL Server, you can just make a copy of the Oracle DAL and then convert it to work with SQL Server. As new business requirements come in, you no longer need to make changes in multiple locations because you only maintain a single set of business objects. And when you are done writing the SQL Server DAL, your application has two functional data access layers. In other words, your application has the means to support two databases. Figure 3 depicts separating data access logic out into a separate DAL:

253-DAL003.jpg

Figure 3 – Business objects with separate data access layer

Design principals in the data access layer

The objective of the DAL is to provide data to your business objects without using database specific code. You accomplish this by exposing a series of data access methods from the DAL that operate on data in the data-tier using database specific code but do not expose any database specific method parameters or return types to the business tier. Any time a business object needs to access the data tier, you use the method calls in the DAL instead of calling directly down to the data tier. This pushes database-specific code into the DAL and makes your business object database independent.

Now wait, you say, all you’ve accomplished is making the business objects dependent on the DAL. And since the DAL uses database-specific code, what’s the benefit? The benefit is that the DAL resides in its own assembly and exposes database-independent method signatures. You can easily create another DAL with the same assembly name and an identical set of method signatures that supports a different database. Since the method signatures are the same, your code can interface with either one, effectively giving you two interchangeable assemblies. And since the assembly is a physical file referenced by your application and the assembly names are the same, interchanging the two is simply a matter of placing one or the other into your application’s bin folder.

Note: You can also implement a DAL without placing it in a separate assembly if you build it against a DAL interface definition, but we will leave that to another article.

Exchanging Data with the DAL

Now the question is: how do you exchange data between your business objects, the DAL, and vice versa? All interaction between your business objects and the DAL occurs by calling data access methods in the DAL from code in your business objects. As mentioned previously, the method parameters and return values in the DAL are all database independent to ensure your business objects are not bound to a particular database. This means that you need to exchange data between the two using non-database-specific .NET types and classes. At first glance it may seem like a good idea to pass your business objects directly into the DAL so they can be populated, but it’s just not possible. The business object assembly references the DAL assembly, so the DAL assembly cannot reference the business object assembly or else you would get a circular reference error. As such, you cannot pass business objects down into the DAL because the DAL has no concept of your business objects. Figure 4 diagrams the situation:

253-DAL004.jpg

Figure 4 – Business objects assembly references the DAL, so the DAL has no concept of business objects

The custom class option

One option is to pass information in custom classes, as long as those custom classes are defined in an assembly that both the business object and DAL assemblies can reference. From an academic standpoint, this approach is probably the truest form of a data abstraction for a DAL because you can make the shared classes completely data-source independent and not just database independent. Figure 5 depicts how the business object assembly and the DAL assembly can both reference a shared assembly:

253-DAL005.jpg

Figure 5 – The business object assembly and the DAL assembly both reference a shared assembly, so they can exchange information using classes and data structures from the shared assembly.

In practice, I find that building out custom classes solely to exchange data doesn’t give you much return for your effort, especially when there are other acceptable options already built into .NET.

The XML approach

You could opt to use XML since it’s the poster child of flexibility and data-source independence and can easily represent any data imaginable. Of course, it also means that you will be doing a lot of XML parsing work to accommodate the data exchange, and I’m not a fan of extra work.

The database interface approach

You could also use the database interfaces from the System.Data namespace to exchange data between business objects and the DAL. Database specific objects such as SqlDataReader , SqlCommand , and SqlParameter are tied to SQL Server, and exposing them from the DAL would defeat the purpose. However, by exposing an IDataReader , IDBCommand , or IDataParameter object you do not tie yourself to particular database so they are an acceptable option, though not my first choice.

From an academic standpoint, the database interface objects do tie you to using a “database management system” even though they do not tie you to a specific database. Pure academics will tell you that the DAL should be “data-source independent” and not just “database independent” so be prepared for that fight if you have a Harvard or Oxford grad on your development team who majored in theoretical application design. Nobody else on the planet cares because the chances of your application moving away from a database system are fairly slim.

My preferred approach: DataSets

Another option for passing information, and the one that I gravitate towards because of its flexibility, is the DataSet. Microsoft created the DataSet class specifically for storing relational information in a non-database specific data structure, so the DataSet comes highly recommended for returning query information containing multiple records and or tables of data. Your work load shouldn’t suffer too significantly from using the DataSet because DataAdapters, which fill DataSets with information, already exists for most database systems. Furthermore, getting data out of the DataSet is fairly easy because it contains methods for extracting your data as tables, rows, and columns.

Also note that a DataSet is technically data-source independent, not just database independent. You can write custom code to load XML files, CSV files, or any other data source into a DataSet object. Additionally, you can even manipulate and move information around inside the DataSet, something that is not possible with the database interfaces from the System.Data namespace.

Exchanging non-relational data

Of course, you also deal with non-relational information when you pass data back and forth between your business objects and the DAL. For example, if you want to save a single business object to the data-tier, you have to pass that business object’s properties into the DAL. To do so, simply pass business object properties into the DAL via native .NET type method parameters. So a string property on your business object is passed into the DAL as a string parameter, and an int property on your business object is passed into the DAL as an int parameter. If the DAL updates the business object property, then you should mark the parameter with the ref modifier so the new value can be passed back to the business object. You can also use return values to return information as the result of a function when the need arises. Listing 1 contains examples of method signatures that you may need in the DAL if you have a Person business object in your application:

Listing 1 – Data access layer method signature examples

Person_GetAll() //Returns a DataSet containing all people records in the database. Person_GetByPersonID(int personID) // Queries the database for the particular user identified by // personID. If the user is located then the DataSet contains a // single record corresponding to the requested user.  If the user // is not found then the DataSet does not contain any records. Person_Save(ref int personID, string fname, string lname, DateTime dob) // Locates the record for the given personID.  If the record exists, // the method updates the record.  If the record does not exist, the // method adds the record and sets the personID variable equal to // the identity value assigned to the new record. Then the method // returns the value to the business layer because personID is // marked with the ref modifier. Person_DeleteInactive()  //Deletes all inactive people in the database and returns a value  //indicating how many records were deleted.

Data service classes

Normally you have one data access method in your DAL for each scenario in which you need to exchange data between a business object and the database. If, for example, you have a Person class then you may need data access methods like Person_GetAll , Person_GetPersonByID , Person_GetByLoginCredentials , Person_Update , Person_Delete , and so on, so you can do everything you need to do with a Person object via the DAL. Since the total number of data access methods in your DAL can get fairly large fairly quickly, it helps to separate those methods out into smaller more manageable Data Service Classes (or partial classes in .NET 2.0) inside your DAL. Aside from being more manageable from a shear number standpoint, breaking down the DAL into multiple data service classes helps reduce check-out bottle necks with your source control if you have multiple developers needing to work on the DAL at the same time. Figure 6 depicts a DAL broken down into three individual data service classes:

253-DAL006.jpg

Figure 6 – Breaking down the DAL into multiple data service classes

Notice that all of the data service classes depicted in Figure 3 derive from a single base class named DataServiceBase . The DataServiceBase class provides common data access functionality like opening a database connection, managing a transaction, setting up stored procedure parameters, executing commands, and so forth. In other words, the DataServiceBase class contains the general database code and provides you with a set of helper methods for use in the individual data service classes. The derived data service classes use the helper methods in the DataServiceBase for specific purposes, like executing a specific command or running a specific query.

Putting theory into practice: the demo application

At this point you should have a descent understanding of what the data access layer is and how it fits into an application from an architectural point of view. Theory is great, but at some point you have to quit talking and start coding. Of course, going from theory to practice is no trivial step, so I wanted to make sure you had a solid example to use as a foundation both in terms of code and understanding.

At the top of this article is a link to a zip file containing two items: a demo application containing a DAL implementation and a Building a Data Access Layer PDF that explains the code in detail. The application is fairly simple, a two page web app that allows you to view / delete a list of people on one page and to add / edit those people on another. However, it does implement all of the design principles that we’ve covered here. Enjoy!

Load comments

Recommended for you

Camilo Reyes

Working with IAsyncEnumerable in C#

IAsyncEnumerable is a powerful interface introduced in C# 8.0 that allows you to work with sequences of data asynchronously. It...

Aneesh Lal Gopalakrishnan

Inline PDF Viewer in an Angular App? Now you can

This article by Aneesh Lal Gopalakrishnan describes the easiest way to integrate an inline pdf viewer into an angular application.…

Julio Sampaio

Creating Templates with Liquid in ASP.NET Core

In this article, Julio Sampaio explains how to use Liquid, an open-source template language, in an ASP.NET Core application.…

About the author

presentation business data layer

Damon Armstrong

Damon Armstrong is a consultant with SystemwarePS in Dallas, Texas. He is also a blogger and author of Pro ASP.NET 2.0 Website Programming and SharePoint 2013 Essentials for Developers . He specializes in the Microsoft stack with a focus on web technologies like MVC, ASP.NET, JavaScript, and SharePoint. When not staying up all night coding, he can be found watching a bunch of kids, studying Biblical topics, playing golf, or recovering from staying up all night coding.

Damon's contributions

  • T-SQL Programming
  • Database Administration

Damon's latest contributions:

Introduction to vue.js with a single page application (spa) in visual studio.

Vue.js is a versatile JavaScript Framework that has many benefits for the developer building .NET web applications. It is, however, not easy to get started...

WPF Menu Displays to the Left of the Window

I remember the first time I used WPF.  It was a while ago.  So long ago, if I am remembering correctly, that there was no...

SharePoint’s Way of Saying Your String is Too Long

I accidentally defined a field in a SharePoint list as a text field instead of a multiline text field and when I went to save...

Data layer implementation and examples to get you started

May 26, 2022

Data layer implementation and examples to get you started

Is your business website optimized for data collection? If it doesn’t have a data layer, then it’s far from optimized. It takes a bit of work but is well worth the effort. Learn how to create a data layer from scratch and see some examples of the implementation in action.

What is a data layer?

A website is composed of layers that interact and relay information from one layer to another. More complex websites may have dozens of layers. At the most basic, websites have these three fundamental layers:

  • Presentation layer: This is the outermost layer and is the part of the website that visitors see and interact with.
  • Data layer: The data layer collects information from the presentation layer, such as a visitor’s geolocation, length of visit, pages navigated, etc. It relays the information to the application layer.
  • Application layer: This comprises tools you add to your website for the web administrator’s use, such as Google Analytics and Facebook Pixel.

Why a data layer matters

Data layers ensure all tools in the application layer receive the same uniform data. It’s all about data consistency. Without the data layer, the application layer receives data straight from the presentation layer. This results in segmented data. Google Analytics and Facebook Pixel, for example, may receive information from different data sets.

Furthermore, data may also be inconsistent if modifications are made to the presentation layer. Data layers are insulated, and data within the layer is unaffected by alterations to the other layers.

Data layer examples

When do data layers come into play? Here are a couple of practical examples.

Let’s say you own a mortgage refinancing website. One page consists of a mortgage calculator that visitors can use to determine loan rates and eligibility based on their income.

In this instance, the data are the numbers visitors enter into the calculator. The information goes from the presentation layer to the data layer. The application layer, consisting of analytic tools, pulls the data from the data layer and yields performance metrics. It can also be set to trigger retargeting ads or special offers based on the specific data type.

Here’s another example: You can set your data layer to track click rates in your call to action. The data layer records this event and sends it to the analytic tools. Your data dashboard is updated, and you have new metrics to analyze. You can also set the system to automatically take a number of responsive actions, such as:

  • Send exclusive email offers to the visitor
  • Have related products appear in the visitor’s recommended list
  • Direct the visitor to a QR code with product-specific details or even full whitepapers

Actions like punching numbers in a digital calculator or clicking a CTA link are events you can configure and assign custom dimensional values to. Set the data and application layer to initiate specific responses, from sending trial offers to special invites to loyalty programs.

How to create a data layer

To create a basic and single data layer (known as a flat data layer), there are three steps to follow:

  • Build the data layer
  • Create a channel to push the data from the presentation layer to the data layer
  • Create a channel to pull the data from the data layer to the application layer

Let’s look at these steps in more detail.

1. Build the data layer

The most basic way to create a data layer from scratch is through JavaScript and to declare an empty array. You can do this using brackets ([ ]) or through a new array constructor method (new Array()). Both perform the same function. Most developers recommend brackets, simply because it’s easier to input.

Once you declare a data layer, the array object goes above the <head> tag. Here’s an example:

presentation business data layer

Photo credit: Makers Aid

An important note here is that the data layer declaration must come before any and all scripts that require a data push or pull from it. The script where you declare the data layer has to precede any third-party tools; this includes consent and tag managers. In other words, never reassign the data layer object . This action will delete all prior pushed data. This may disrupt the data as it moves to the application layer, creating inconsistencies.

Also, if you create multiple data layers, they need to be assigned different but uniform names. If you name the first one datalayer1, for instance, then follow the same formula by naming subsequent layers datalayer2, datalayer3, etc.

2. Create a data push

The next step is to create a data push to the data layer. The simplest method is to use JavaScript’s Array.push(). Furthermore, you can use the dataLayer.push() to push multiple data sets to the data layer. Be sure to distinguish nearby key and value pairs using a comma. Each data stream should also be surrounded by curly brackets. When implemented correctly,  the data is incorporated into the array object end in the order you push them.

Here’s an example of creating a data push to the data layer:

presentation business data layer

3. Pull data

When pulling data from the data layer, you’ll most likely use a tag management system like Tealium or Google Tag Manager. From here, the data enters a downstream network where it’s absorbed by a suite of analytic and metric tools.

If you need to access data in the data layer, you can reference the array object’s name. Here’s an example of what this may look like for a data layer aptly named datalayer.

presentation business data layer

Simplify data layer implementation with Lytics

Try Lytic’s Cloud Connect today. Get 24/7 access to your data no matter where you’re at. Create efficient multi-layer data layers, produce data layer extensions, and completely eliminate data silos. Whether your team operates in-house or remotely, we make data layer implementation an intuitive process. Try Lytics risk-free for 30 days by signing up for a trial today.

Get started with Lytics Cloud Connect

Mark Hayden

Share this article

Get value straight to your inbox

Get the latest news, freshest insights, and newest product updates direct from Lytics experts.

We respect your information. Please see our privacy policy to learn more.

Recommended articles powered by Lytics

presentation business data layer

Stack Exchange Network

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

Q&A for work

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

Is validation part of presentation layer or business logic? [duplicate]

We're working on a new project (backend, API), following the "clean code" and "clean architecture" principles (described in Robert Martin's books), dividing our application into presentation, domain, and data layers. The presentation layer handles routes and data formatting, while the domain layer contains the business logic and accesses data when needed.

We're debating whether data validation should occur in the presentation layer (to validate user input directly) or the domain layer (as part of business logic). I'm convinced it belongs to presentation, since we want to validate raw user input and provide hints what's wrong, and if we do it in domain layer we may be dealing with transformed data that's vastly different from user input, hence we can't give clear hints on what should be fixed. My colleagues however maintain validation is part of business logic and should be part of the domain layer.

By validation I mean checks like "value is integer and in range from 1 to 100" or "string matches this format".

Can anyone clarify which approach is the best and recommend references for further understanding this issue?

  • domain-driven-design
  • clean-architecture

LNK's user avatar

  • See also softwareengineering.stackexchange.com/a/348916 . Or in short, the answer it is part of both. –  Doc Brown Commented Feb 8 at 23:12
  • I would recommend thinking about where you draw the system boundary. On the outside of that boundary, data is untrusted and may be invalid, often in form of DTOs. Internally, you want to rely on the data being valid, often in form of meaningful objects. So that boundary must perform validation+conversion and reject illegal inputs. In web applications, the client cannot be trusted so that boundary is necessarily in the backend, but the part in the backend where validation happens might not yet be the core "business logic". Any frontend validation is just for UX, not for correctness. –  amon Commented Feb 8 at 23:36
  • 1 Please see this answer –  John Wu Commented Feb 9 at 1:31

4 Answers 4

It's an unfortunate fact that the same validation rules often have to be applied and checked repeatedly at different places in the same application.

The validation rules themselves may often be identical, but the reaction to invalid input will not necessarily be the same in each place, and the timing of the enforcement will not necessarily be the same.

For example, as you say, validation rules often have to exist at the presentation layer in order to give immediate feedback to the computer user, and to allow everyday input errors to be corrected. There may be logic that is specific to the presentation layer, such as highlighting erroneous fields, help text which explains acceptable ranges of input, and so on.

However, some kinds of rule may also be inherently enforced at deeper layers. For example, certain fields may have length limits at the storage layer.

For technical reasons, constraints defined at the storage level are often considered the primary or originating constraint, and any duplication of the constraint that exists at the presentation layer is merely an auxiliary or slave version of the same constraint.

What I'm trying to say is that the primary site of enforcement for different constraints can be intrinsically more local to one layer or another, so that it isn't possible to set out with the idea of simply placing all constraints merely in one layer.

However, for reasons of application responsiveness, to ensure that the user is given an opportunity to fix or react to violations as soon as possible, to avoid part-triggering a heavyweight process that will subsequently crash out, or just to try and ensure there is at least one place in source code where a consolidated view of all the constraints is available, it may be considered desirable to have auxiliary and pre-emptory enforcement of constraints at the presentation layer, and the primary constraint at a deeper layer would be triggered only as a backstop when developer error meant the auxiliary/pre-emptory constraint was not properly applied.

And because the hitting of the primary constraint now implies developer error, the programmed reaction of the application may be very different (and involve the alerting of system supervisors) than when only the auxiliary constraints are hit in the presentation layer (which are likely considered normal and lead only to normal user feedback). So even though the criteria for the constraints are the same, the reaction isn't.

Because we now have this concept of primary and auxiliary sites at which constraints are enforced, and because of the possibility of developer error in synchronising the auxiliary constraints with the primary ones, and perhaps for additional architectural reasons, there can often end up being even more than two enforcement sites for the same constraint. There can be a primary site and also multiple auxiliary sites.

And although above I have given an example of the primary site for a constraint being in the storage layer, in some cases, the primary site for a constraint may not even be in the computer system under development, or even originate in the same organisation. For example, the constraint may originate in the law of the land, or in the bureaucratic rules of a different organisation. So even if there was only one site of enforcement in your source code, there may still be additional sites outside the source code in question, and those outside enforcement sites may in fact be the primary enforcement sites which your source code has to reflect (and pre-empt).

For any kind of business information system, it isn't generally possible to avoid having multiple representations of constraints and multiple sites of enforcement in source code, the synchronisation of which has to be handled manually by the developers.

Rather than thinking of this as a wasteful kind of redundancy that can be driven out by better design, consider that each site of enforcement is often encountered at a different time in an overall schedule of processing, and there may be different programmed consequences of a violation being detected at different sites even though the criteria for the violation itself is essentially the same.

Steve's user avatar

You're getting sidetracked by thinking of validation as a single indivisible concept and assuming that it must belong to one specific location.

The truth is that different kinds of validation exist, and different validations belong in different places. Just some quick examples:

  • If we want to block people under 18 from renting certain books, that's a business rule, and therefore it belongs to the application layer (or domain, for the purpose of this example domain/application is context-dependent)
  • Did the incoming API request contain correct parameter values (e.g. making sure an int parameter is not "banana" )? That's endpoint validation and belongs in the API layer.
  • Does this string value contain any encoded characters that the persistence store can't handle? This is the kind of validation that you'd put in the persistence layer.
  • Do we want to give the user immediate feedback about their input before they try to submit the form? That would require validation rules to be executed in the frontend. That kind of validation would inherently need to live in the frontend (unless you are okay with polling the BE for validation, which is not particularly efficient)

Like so many things, this isn't a predetermined answer that you can find online and then apply in your codebase. This is something that needs you to consider your own specific use case and find what works best for you .

By validation I mean checks like "value is integer and in range from 1 to 100" or "string matches this format"

These do sound to me like they're business rules, so the application layer is definitely a correct place for them.

Then there's the question of whether you want to also bake validation into the frontend. The benefit of doing so would be that you can provide the user immediate feedback instead of waiting for them to submit the form. The drawback is that you have to develop the same validation a second time (and usually you can't reuse logic between FE/BE as they tend to use different languages).

I strongly advise you don't take a FE-only validation approach, because FE-only validation can be circumvented by a malicious user who knows how to use their browser's dev tools or craft their own requests (e.g. using PostMan). That being said, if malevolent use does not cause a problem for anyone except the user themselves, you can argue that you don't need to defend against malevolent use. But that is a dangerous call to make if you're wrong.

Flater's user avatar

  • Thanks for your reply! By presentation layer as I said in the question I meant not frontend, but the layer of backend API where requests are received, decoded, passed to business logic layer and then formatting response –  LNK Commented Feb 9 at 10:31
  • @LNK That's a reasonable ambiguity to point out but it's the same principle at play regardless –  Flater Commented Feb 11 at 9:15

If what you are doing is parsing some general purpose representation to ensure that it conforms to some schema, you will normally want that to happen as close to the process boundary as you can conveniently manage.

If what you are doing is comparing the information to some current policy, or performing a comparison of that information to other information that has already been collected (ie: what's in the database), then that will normally be a domain model concern.

Example: some field in the input message is supposed to be RFC 4122 compliant UUID ? That's a parsing concern that you put near the boundary. The UUID is supposed to match one of the known productId values in our system? That's a domain model concern.

If I could look back at one thing that improved my take on validation the most, it’s adherence to a closure of operations. I’d encourage you to go back to those sections on command/query separation and closure of operations in the Big Blue Book. Once I adhered to those two concepts, validation was merely another step in reporting the success or failure of an operation, and like many good simplifications, a host of symptoms I mistook for separate diseases just went away. -- Jimmy Bogard, 2009

VoiceOfUnreason's user avatar

Short answer: Both!

This is what we used to call Defensive Programming. Checking that that the Data we've being given will "fit" into wherever we need to put that Data next and rejecting it if it doesn't.

At the Business level, we need to ensure that, say, a Transaction amount is numeric and has a "sensible" value, that a given UserId actually does exist in the backend system, that the Product whose Id we've been supplied actually exists and we've got enough of them to meet this order.

At the Presentation level, it's "nice" to check all of these things and give "immediate" feedback where we can and, indeed, most modern users would expect us to do just that. But that's for their benefit, as part of the User Experience, not ours , as part of our protecting our systems against duff Data.

In the world of the Web Application, nothing from the client should be trusted. All the JavaScript (or whatever) validation code in the World can now be "edited away" by a sufficiently-determined user, armed with nothing more than their web browser. Question: If you send an HTML SELECT list to the User to choose an option from, do you validate the value that comes back? You should ...

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

  • The Overflow Blog
  • Mobile Observability: monitoring performance through cracked screens, old...
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites

Hot Network Questions

  • Duties when bringing Canadian goods to US in luggage
  • FCC regulations stipulate that personal electronic devices must be set to airplane mode during flight. Are there any exceptions?
  • ESTA is not letting me pay
  • Seinfeldisms in O.R
  • Does it pay to put effort in fixing this problem or better reinstall Ubuntu 24.04 from scratch?
  • Lore reasons for being faithless
  • What is opinion?
  • Determining Error Rate of Phase Shift Keying via Monte Carlo Simulation
  • Making a battery power supply for a portable Raspberry Pi computer
  • Where did I go wrong in using Kirchhoff's Voltage Law for this circuit?
  • How much easier/harder would it be to colonize space if humans found a method of giving ourselves bodies that could survive in almost anything?
  • What does this translated phrase convey "The heart refuses to obey."?
  • In Top, *how* do conjugate homorphisms of groups induce homotopies of classifying maps?
  • Took a pic of old school friend in the 80s who is now quite famous and written a huge selling memoir. Pic has ben used in book without permission
  • Fast algorithm to obtain an orthogonal vector to a set of vectors
  • Why is simpler prose more popular these days?
  • Why is GParted distributed as an ISO image? Is it to accommodate Linux needs as well as Windows needs?
  • Accidentally Removed the Shader Editor: How to Restore It?
  • Word for a collection of awards, such as an Olympic athlete’s earned medals
  • Why does my shifter say the wrong gear?
  • Why are IC and IE different? Aren't the two 1k ohm resistors in series and thus the current through them should be the same?
  • What is this device in my ceiling making out of battery chirps?
  • How to set the option `top' in tcb only in first breakable part in PikaChu tcolorbox?
  • 70s-80s animation with an island of robots

presentation business data layer

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

Collectives™ on Stack Overflow

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

Q&A for work

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

Get early access and see previews of new features.

Dependency injection between business layer and presentation layer

I am trying to follow clean architecture in my software. I have implemented 3 layers: data layer, business layer and presentation layer.

As far as I understand dependency will follow outside to inside like P->B->D.

But my question is should I do a singleton data layer executor injection into presentation? Doesn't that break this logic?

Or without DI, only create an abstraction between layers I think creates tight coupling.

So referring to some data layer dependency from inside the business layer - doesn't that make the layers tightly coupled?

  • design-patterns
  • dependency-injection

marc_s's user avatar

2 Answers 2

In the clean architecture, the inner layers are logic, not infrastructure.

When the business layer instantiates the data layer, it injects any infrastructure dependencies that it requires.

Similarly, when the presentation layer instantiates the business layer, it passes in any infrastructure dependencies that it requires. This is how the business layer gets the infrastructure it needs to pass to the data layer.

And initially, when the application/system instantiates the presentation layer, it passes in the infrastructure that it will need. The humble object pattern should be used to implement these dependencies, because they are the only part of the system that can't be tested independently from infrastructure.

Matt Timmermans's user avatar

It depends on what you mean by "tight coupling". Following the 3 layered architecture is ok for the data layer to be a dependency on the business layer and the business layer to be a dependency on the presentation layer.

Instead of injecting a concrete class, you can always define the dependency injection on an Interface. With this, you can always switch the implementation as long as you follow the agreed interface.

However, my experience tells me that you rarely or never do this for a basic and regular 3 layered architecture. You have always a single Service and a single Repository/DAO implementation so having an Interface for each of them is kind of redundant and useless.

I think that the most important thing when you work with 3 layered architecture is to never bypass layers. Examples:

  • You should never make the presentation layer depend directly on the data layer. Always go through the business layer.
  • The relation between the layers should be always 1:1. This means you should never make a Controller call a Service that is associated with another Controller.

Not following these rules will for sure make your code incredibly hard to read and understand. Of course, for every rule, there is an exception, but try to stick to them.

João Dias's user avatar

  • yes , right now presentationlayer instanties an abstract class(implements an interface for pressntationlayer) which resides inside the business layer for example, is that wrong?,,, also presentation goes to business layer then data layer, (my question data layer has a module dependency back to businesslayer? so data layer push data back to business so its tight coupled?) –  wipesax360 Commented Sep 10, 2021 at 14:30
  • public class ViewModel<T> extends GenericRouter { IPresentation ip = new BusinessUseCaseImpl(); is that wrong? –  wipesax360 Commented Sep 10, 2021 at 14:35
  • Well, in a project leveraging dependency injection, any instantiation of classes that should be beans is indeed wrong. You should only declare the dependency and the framework (be it JakartaEE, Spring or other) will take care of the injection. –  João Dias Commented Sep 10, 2021 at 20:51
  • Regarding "my question data layer has a module dependency back to businesslayer? so data layer push data back to business so its tight coupled?" the answer is yes that shouldn't be the case. The business layer should have the data layer as a dependency, but the data layer should not have a dependency back to the business layer. In fact, this is basically a circular dependency which is not allowed in Frameworks like Spring ( baeldung.com/circular-dependencies-in-spring if you want to read more). –  João Dias Commented Sep 10, 2021 at 20:57
  • ok so without DI, i think that relation between layer can be set up with interfaces and abstract classes.? bu please check the question i added some concrete class instatiasions inside viewmodels&businesslayer class. viewmodel creates a businessinterface and call its method, then business layer again call to datalayer within itself. this is manual dependency injection. but i think this way true. i will replace it dagger soon –  wipesax360 Commented Sep 10, 2021 at 22:30

Your Answer

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

Sign up or log in

Post as a guest.

Required, but never shown

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

Not the answer you're looking for? Browse other questions tagged java design-patterns dependency-injection or ask your own question .

  • The Overflow Blog
  • Mobile Observability: monitoring performance through cracked screens, old...
  • Featured on Meta
  • Announcing a change to the data-dump process
  • Bringing clarity to status tag usage on meta sites
  • What does a new user need in a homepage experience on Stack Overflow?
  • Staging Ground Reviewer Motivation
  • Feedback requested: How do you use tag hover descriptions for curating and do...

Hot Network Questions

  • Why is the !? annotation so rare?
  • Overstayed Schengen but can I switch to US passport?
  • Why are IC and IE different? Aren't the two 1k ohm resistors in series and thus the current through them should be the same?
  • Does Gravity Well work with Blade Ward?
  • What is this 3 terminal white + grey surface mount device?
  • What is the highest apogee of a satellite in Earth orbit?
  • Why is Namibia killing game animals for food rather than allowing more big game hunting?
  • Why is GParted distributed as an ISO image? Is it to accommodate Linux needs as well as Windows needs?
  • How is it possible to know a proposed perpetual motion machine won't work without even looking at it?
  • Is this screw inside a 2-prong receptacle a possible ground?
  • Is it illegal to use a fake state ID to enter a private establishment even when a legitimate ID would've been fine?
  • The part "<->" in \draw[<->] doesn’t work
  • Who owns code contributed to a license-free repository?
  • Which Mosaic law was in the backdrop of ceremonial hand-washing in Mark 7?
  • Why does my shifter say the wrong gear?
  • Does it pay to put effort in fixing this problem or better reinstall Ubuntu 24.04 from scratch?
  • What is a "hard-boiled turtle-slapper"?
  • Cannot open an HTML file stored on RAM-disk with a browser
  • How to perform correlation & regression analysis using both 5-point likert scale and "Yes/No/Maybe" questionnaire?
  • Would it be Balanced to Give Everyone Warlock Slots for Casting Racial Spells?
  • Journal keeps messing with my proof
  • Barnum Effectus
  • How specific does the GDPR require you to be when providing personal information to the police?
  • How is an inverting opamp adder circuit able to regulate its feedback?

presentation business data layer

  • Help Center

What is a Data Layer? How Data Layers Work

An introduction to the data layer: what it is, how it works, and how it can benefit your business.

When talking about setting up analytics tracking for your website or app, you’ll often inevitably hear the word “data layer” thrown around. While it sounds mysterious, it’s actually a simple concept that can be understood by developers and marketers alike.

A data layer is a JavaScript object that collects data on your website in a standardized way. Every tool you hook up to your website — analytics, heatmapping, live chat, etc. — accesses this one layer of data, which ensures two things:

Each tool gets the data it needs.

The data each tool uses is the same.

Here’s an example from W3 that shows what a data layer might look like:

what-is-a-data-layer1

This data layer contains multiple values that will populate automatically when a visitor arrives at your site, such as page name (PageID), URL, geographic data, and more. The code that makes up this data layer is what your analytics tools access to get the data they need. Because each tool is accessing this same bit of code, you’ll know that they’re all working with consistent data.

The consistency you get from implementing a data layer is invaluable as the data you collect in your data layer moves from one tool to another. But data layers are complex, technical things that require quite a bit of work from multiple teams to get up and running.

If you want to use a data layer, you first need to understand its role and how it works. Then, you can put it to work.

What is a data layer?

A data layer is a layer of your website which contains all of the data that gets generated by visitors engaging with your website. Not all websites have a data layer, but having one enables more reliable and flexible data collection.

What does a data layer do?

The role of a data layer is to provide a reliable place to collect data as its generated. This role impacts three main areas: your website, your tools, and your organization.

Let’s say you’re the director of marketing at a fledgling SaaS startup looking to grow quickly. You just launched a fancy new website, and you need to ensure that the data you collect is consistent. So, before launch, you collaborated with your developers to create a data layer. Here’s how that data layer will affect your growth moving forward.

Reliably collects all data within the website

All websites, software, and applications can be thought of as a series of layers, each with its own purpose. Let’s say your recently launched website, like many websites, is made up of three layers:

The presentation layer , which is what the visitor to your website sees. It’s made with HTML and CSS.

The data layer , which is the layer for collecting and managing the data that gets produced. It’s a JavaScript object, often an array.

The application layer is made up of all the tools you connect to your website, like Google Analytics, Facebook Pixel, and more. These are usually JavaScript snippets.

Every website has a presentation layer, and almost every site has some sort of application layer. Not every site has a data layer, though. And without a dedicated data layer, your data collection would be dependent on one of the other layers.

If you rely on your presentation layer to collect data, through processes like DOM scraping or CSS selectors , any change you make to the design or structure of your site will impact the data you collect. This can turn even small design changes into huge data headaches.

Relying on the application layer means allowing each tool to collect its own data. This would likely lead to each tool collecting slightly different data, which can cause problems down the line when you’re trying to make sense of your website’s overall performance. For instance, a page in Google Analytics might have a different name than in Mixpanel.

A data layer avoids these issues by being the one place that collects data. It’s insulated from changes to other layers, so your stream of data is not thrown off by switching tools, design, or layout.

Integrates with other tools to ensure data quality

A data layer also makes sure each tool receives the data it needs to do its job. Say your new site needs some web analytics, so you turn to Google Analytics as well as Google Tag Manager (GTM) as your tag management system.

When you implement a data layer, each of these tools receives the same data. Here’s a screenshot of Segment’s data layer on our home page:

what-is-a-data-layer2

Here, the data layer array starts with “dataLayer” and lists out a few values. All of these values, like “Viewed Segment | Customer Data Platform (CDP) Page” can be accessed by GTM, Google Analytics, and many other tools for later analysis.

All of your tools will refer to this event as “Viewed Segment | Customer Data Platform (CDP) Page.” And they will all log that this event was driven by direct traffic (i.e., typing the URL) because “referrer” is left blank. In short, the naming convention is consistent across all the tools you use.

Your data layer can get much more complex than this example, hence the need for developers. But the fact that each tool is working with the same data will make using your suite of tools much easier to work with.

Note: you can find most sites’ data layer in a pretty simple way. In Chrome, right-click the web page and select “Inspect.” Then, navigate to “Console.” If you see anything there, right-click and select “Clear Console.” Then, type in “dataLayer” and press enter.

Helps create a unified data strategy within an organization

A data layer can align teams around one strategy for data collection. The creation of a data layer is a complex, time-intensive process that requires collaboration between marketers and developers. Marketers bring the business knowledge about what data to collect, while developers bring the technical know-how to actually make the data layer.

You, as the director of marketing, would lay out your core business requirement and objectives. Say you need to run targeted remarketing campaigns, personalize automated emails and chatbots, and run A/B tests on landing pages.

The developers then take these requests and figure out a way to fold them into your data layer (later, we’ll go into more detail on how this process works). Together, you create a single strategy for collecting data that the entire organization can rely on.

What are the benefits of a data layer?

Put simply, a data layer can make your data more reliable and enhance functionality and optimization efforts. It’s an insulated layer of your website focused solely on data. What’s more, it not only relies on but also encourages inter-team alignment around data strategy . In the end, you gain alignment among all your tools and all your teams around how data gets collected on your website.

Your data layer needs consistent naming conventions. For example, marketers and developers need to agree on a page name. It could be “pageID” or “pageName” or just “name.” By laying this out from the get-go, not only will both teams know how to refer to that specific value but so will every tool in your analytics stack.

But agreeing to a naming convention is just scratching the surface of your data structure. To create a good data layer, your teams need to agree on what data to collect. Page name is a fairly default value, but what about something more granular and specialized? Ecommerce brands, for instance, might need to consider values like “ProductID” or even “ProductColor.”

Creating a data layer forces you to ask yourself, “What data is important to us as a business?” You then answer that question together by deciding on what data to collect with your data layer.

Quality data and infrastructure

Consistent, reliable data is quality data. A data layer ensures that at the point of collection, the data you decide to track will follow a set of naming conventions you decide upon as a team. Every tool that uses this data from that point on will be working from the same playbook.

The data in Google Analytics will match the data in GTM, which will match the data in Mixpanel, which will match the data in Hotjar, and on and on. This level of data governance across tools is scalable as you add more tools and change business objectives. With a data layer, you’ll be building your analytics stack on a solid foundation of quality data.

Flexibility

Even though it makes a solid foundation, your data layer is not a stiff, unchanging thing. A good data layer is flexible and provides the ability to grow your analytics and optimize as you see fit.

Think of your data layer as a living thing. Once set up, it can grow and change as your business does, and there are likely many future use cases for your data layer that you may not be aware of now. If a value you’re tracking proves to be less important than you thought it would be, you can strike it. If you need to add a value, you can do so.

At the same time, data layers are insulated from the other layers of the website. Changes you make to just about anything else — from design to structure to the tools you use — won’t affect it. So redesign your site to your heart’s content. Try out new tools and drop ones that don’t work. Making a huge data migration from Adobe Analytics to Google Analytics? No sweat. Your data layer will remain solid and consistent throughout.

What does a data layer contain?

In short, a data layer contains the data that gets generated on a web page. Let’s look at the W3 example again:

what-is-a-data-layer3

A data layer is a JavaScript object called an array, shown here as “digitalData.“ You may also see it around the web as ”dataLayer“ for GTM and ”utag“ for Tealium. Which one you use is a question for your developers. The point is that they all do the same job of starting the data layer.

Within the array is a set of JavaScript objects, which are made up of keys and values (also called variables). In this example from W3, one of the keys is “PageID,” and its value is “Home Page.” You can think of the key as the question and the value as the answer. When a visitor lands on the Home Page, the data layer goes down the list of questions and populates answers where it can.

Looking at this from a business perspective, these keys can be seen as the data your business considers important to collect. For example, an e-commerce company might use these keys in their data layer:

pagename, to log a page title like “Checkout Page”

page category

checkout, to log if a checkout occurred

product name

product price

The data layer will fill in the answers for each of these. Then, every analytics tool will gain access to these answers.

How do you get started on creating a data layer?

Building and implementing a data layer is something entire careers are built on, so there’s a lot more nuance to doing so than what we can cover here. Stuart Roskelley is a veteran at implementing data layers, and he describes the process as following five main steps:

Identify which of your vendors need data.

List which tools will need unique or complex data.

Create a list of “[tool]-neutral variables” that can be used across all your tools.

Organize these lists.

Implement the data layer.

Read Stuart’s guide for more information on each of these steps. It’s important to note that these are broad steps that gloss over a lot of the hard work of interdepartmental compromise. This process should be one of collaboration throughout, taking into account the goals, concerns, and pain points of everyone involved.

In other words, there will be a lot of up-front effort. Jason Case , director of analytics implementation at Blast Analytics & Marketing, says, “It is common for [the process of implementing a data layer] to take 1-2 weeks to plan and then 2-4 weeks to implement.” And even then, you’re not quite done.

You need to create a plan to maintain and regularly update your data layer. This can be a spreadsheet or document with all the information about what data is being collected and why. Revisit the plan as frequently as you need to ensure that you’re collecting the most relevant data.

Creating a strong data infrastructure

A data layer is just one part of your business’s data infrastructure. You can think of it almost like the “front line,” ensuring that the data you collect is consistent and reliable as it collects it. From there, your customer data goes on a journey to get used in your suite of analytics tools, data warehouses, business intelligence platforms, marketing automation tools, and more.

Without help, managing this flow of data can be a daunting task. That’s where customer data platforms (CDPs) like Segment come in. Segment makes it simple to gather all of your customer data into one place, standardize it, and then send it to where it needs to go. And having all this data in one place allows you to understand your customers on a deep level so you can provide them with a great customer experience.

Test drive Segment

Test drive Segment CDP today

It’s free to connect your data sources and destinations to the Segment CDP. Use one API to collect analytics data across any platform.

Recommended articles

Want to keep updated on segment launches, events, and updates.

We’ll share a copy of this guide and send you content and updates about Twilio Segment’s products as we continue to build the world’s leading CDP. We use your information according to our  privacy policy . You can update your preferences at any time.

Thank you for subscribing!

IMAGES

  1. Where to Use Tiers and Layers Graphics in a Presentation

    presentation business data layer

  2. A Quick Look at Big Data Layers, Landscape, and Principles

    presentation business data layer

  3. Architecture of Business Layer working with Entity Framework

    presentation business data layer

  4. SAP Architecture

    presentation business data layer

  5. Implementing A Data Model and Business Layer that Supports State

    presentation business data layer

  6. Where to Use Tiers and Layers Graphics in a Presentation

    presentation business data layer

VIDEO

  1. Time Distribution of Presentation| PowerPoint presentation| Business communication Chapter 11

  2. The Data Layer in #Marketing

  3. Business Builder Overview: SAP Datasphere

  4. ⭐️StratioBD included in Gartner’s 2023 Data Integration Tools Magic Quadrant

  5. Textual Presentation l Presentation of Data l Class 11 Statistics by N.Dhali

  6. OSU-OKC Career Path Presentation

COMMENTS

  1. What Is Three-Tier Architecture?

    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.

  2. c#

    The presentation layer should only be concerned about presenting data, not about how to retrieve it. Suppose you move your whole database into CSV files (I know, crazy idea), then your presentation layer should not be aware of this at all. So ideally, you have a business layer method that returns just the data you want to show to the user.

  3. Business-Logic Layer

    The Business-Logic Layer (BLL) is a component of a software architecture that is responsible for implementing the business logic of an application. It sits between the presentation layer (e.g., the user interface) and the data access layer (e.g., the database), and is responsible for processing and manipulating data before it is presented to ...

  4. Understanding Layered Architecture: A Comprehensive Guide

    Layers: Presentation Layer: ... Contains the application's business rules and logic. Data Access Layer: Manages data storage, retrieval, and communication with databases. 2. Dependencies:

  5. 3-tier architecture

    Here you combine logic with the data from the data layer. This layer is responsible for calculations and decisions before sending the data to your presentation layer. The application layer is often called the business layer. This is a small heritage from the time we had the DLL (data layer library) and the BLL (business layer library).

  6. 1. Layered Architecture

    For example, assume the presentation layer responds to a request from the user to retrieve customer data. The presentation layer passes the request to the business layer, which simply passes the request to the persistence layer, which then makes a simple SQL call to the database layer to retrieve the customer data.

  7. Presentation Domain Data Layering

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

  8. 3 Layered Architecture

    2. Three Tier/Layer Architecture Design Components. As we have already seen, tier is the sum of all the physical components. We can separate the three tiers as Data Tier, Business Tier and Presentation Tier. Data Tier is basically the server which stores all the application's data.

  9. Walkthrough: Creating the Data Access and Business Logic Layers in ASP

    One of these patterns is to separate the data-access code from the business-logic code that governs access to the data or that provides other business rules. In this pattern, these two layers are separate from the presentation layer, which consists of the pages that the Web site user accesses to view or change data.

  10. Presentation Layer in OSI model

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

  11. Creating a Business Logic Layer (C#)

    In this tutorial we'll see how to centralize your business rules into a Business Logic Layer (BLL) that serves as an intermediary for data exchange between the presentation layer and the DAL. Introduction. The Data Access Layer (DAL) created in the first tutorial cleanly separates the data access logic from the presentation logic. However ...

  12. .NET Application Architecture: the Data Access Layer

    In the classic three tier design, applications break down into three major areas of functionality: The data layer manages the physical storage and retrieval of data. The business layer maintains business rules and logic. The presentation layer houses the user interface and related presentation code. Inside each of these tiers there may also ...

  13. The Three Layered Architecture. Layers

    Data Access Layer (DAL). This layer is separated into two: DAL abstractions and DAL. The data access layer is the layer that implements the communication with the data source (usually a database).

  14. Where do presentation, business logic, and data access layers and MVC

    Nowadays, with modern frontend frameworks such as Angular, React, and Vue, does the entire presentation layer run on client side, and do the entire business logic layer and the entire data access layer run on the server side? Business logic and data access happen on the server side, that is correct. Angular, et.al. handle code on the frontend.

  15. Data layer implementation and examples to get you started

    Create a channel to push the data from the presentation layer to the data layer; Create a channel to pull the data from the data layer to the application layer; Let's look at these steps in more detail. 1. Build the data layer. The most basic way to create a data layer from scratch is through JavaScript and to declare an empty array.

  16. Separation of Presentation layer from Business layer

    3. Obviously the buisness layer must know what progress has been made. It must then either tell the presentation layer when progress has been made or the presentation layer must ask the business layer. Whichever you prefer. The key point is that the presentation layer should not be making a judgement of what progress has been made and the ...

  17. Is validation part of presentation layer or business logic?

    The presentation layer handles routes and data formatting, while the domain layer contains the business logic and accesses data when needed. We're debating whether data validation should occur in the presentation layer (to validate user input directly) or the domain layer (as part of business logic).

  18. java

    It depends on what you mean by "tight coupling". Following the 3 layered architecture is ok for the data layer to be a dependency on the business layer and the business layer to be a dependency on the presentation layer. Instead of injecting a concrete class, you can always define the dependency injection on an Interface.

  19. What is a Data Layer? How It Works & Benefits of Having One

    A data layer is a JavaScript object that collects data on your website in a standardized way. Every tool you hook up to your website — analytics, heatmapping, live chat, etc. — accesses this one layer of data, which ensures two things: Each tool gets the data it needs. The data each tool uses is the same.