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.

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.

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

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

presentation layer data access layer

11 July 2006

518779 views

Printer friendly version

.NET Application Architecture: the Data Access Layer

Find out how to design a robust data access layer for your .NET applications.

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

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!

Automate database deployments

Standardize team-based development - Prevent rework and conflicts, build consistency and quality into your code, and gain time for development that adds value, with standardized best practices for database development.

Find out more

Subscribe for more articles

Fortnightly newsletters help sharpen your skills and keep you ahead, with articles, ebooks and opinion to keep you informed.

Rate this article

presentation layer data access 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.

Follow Damon Armstrong via

View all articles by Damon Armstrong

Load comments

Related articles

presentation layer data access layer

Inline PDF Viewer in an Angular App? Now you can

presentation layer data access layer

The Zen of Code Reviews: Review As If You Own the Code

Using c# to create powershell cmdlets: the basics.

  Layer 6 Presentation Layer

De/Encryption, Encoding, String representation

The presentation layer (data presentation layer, data provision level) sets the system-dependent representation of the data (for example, ASCII, EBCDIC) into an independent form, enabling the syntactically correct data exchange between different systems. Also, functions such as data compression and encryption are guaranteed that data to be sent by the application layer of a system that can be read by the application layer of another system to the layer 6. The presentation layer. If necessary, the presentation layer acts as a translator between different data formats, by making an understandable for both systems data format, the ASN.1 (Abstract Syntax Notation One) used.

OSI Layer 6 - Presentation Layer

The presentation layer is responsible for the delivery and formatting of information to the application layer for further processing or display. It relieves the application layer of concern regarding syntactical differences in data representation within the end-user systems. An example of a presentation service would be the conversion of an EBCDIC-coded text computer file to an ASCII-coded file. The presentation layer is the lowest layer at which application programmers consider data structure and presentation, instead of simply sending data in the form of datagrams or packets between hosts. This layer deals with issues of string representation - whether they use the Pascal method (an integer length field followed by the specified amount of bytes) or the C/C++ method (null-terminated strings, e.g. "thisisastring\0"). The idea is that the application layer should be able to point at the data to be moved, and the presentation layer will deal with the rest. Serialization of complex data structures into flat byte-strings (using mechanisms such as TLV or XML) can be thought of as the key functionality of the presentation layer. Encryption is typically done at this level too, although it can be done on the application, session, transport, or network layers, each having its own advantages and disadvantages. Decryption is also handled at the presentation layer. For example, when logging on to bank account sites the presentation layer will decrypt the data as it is received.[1] Another example is representing structure, which is normally standardized at this level, often by using XML. As well as simple pieces of data, like strings, more complicated things are standardized in this layer. Two common examples are 'objects' in object-oriented programming, and the exact way that streaming video is transmitted. In many widely used applications and protocols, no distinction is made between the presentation and application layers. For example, HyperText Transfer Protocol (HTTP), generally regarded as an application-layer protocol, has presentation-layer aspects such as the ability to identify character encoding for proper conversion, which is then done in the application layer. Within the service layering semantics of the OSI network architecture, the presentation layer responds to service requests from the application layer and issues service requests to the session layer. In the OSI model: the presentation layer ensures the information that the application layer of one system sends out is readable by the application layer of another system. For example, a PC program communicates with another computer, one using extended binary coded decimal interchange code (EBCDIC) and the other using ASCII to represent the same characters. If necessary, the presentation layer might be able to translate between multiple data formats by using a common format. Wikipedia
  • Data conversion
  • Character code translation
  • Compression
  • Encryption and Decryption

The Presentation OSI Layer is usually composed of 2 sublayers that are:

CASE common application service element

Sase specific application service element, layer 7   application layer, layer 6   presentation layer, layer 5   session layer, layer 4   transport layer, layer 3   network layer, layer 2   data link layer, layer 1   physical layer.

This browser is no longer supported.

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

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

When you work with data in ASP.NET, you will benefit by using common software patterns. 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.

A Visual Studio Web site project with source code is available to accompany this topic: Download .

ASP.NET can provide separation between data access, business logic, and presentation in several ways. For example, the data source model, which includes server controls such as the LinqDataSource and ObjectDataSource controls, separates the presentation layer from the data-access code and the business logic.

Another pattern is to include the data-access logic directly in the ASP.NET pages (the presentation layer). For example, you might write ADO.NET code in the ASP.NET page's code-behind page or use the SqlDataSource control. This approach tightly couples the data-access logic with the presentation layer.

The recommended approach is to separate the data access logic from the presentation layer. This separate layer is referred to as the data-access layer. The data-access layer can be implemented as a separate Class Library project. However, you can also use tools in Visual Web Developer that can generate a data-access layer for you.

You cannot create a class library project in Microsoft Visual Web Developer Express. However, you can create a separate project by using Visual Basic Express or Visual C# Express and then include the output from that class as an assembly (DLL) in the Web site.

If your Web site displays or updates data, you should create a data-access layer and business-logic layer before creating the user interface.

A data-driven Web application usually includes a data-access layer by using typed datasets or entity classes that represent the data. It also includes a business-logic layer that enforces custom business rules. Finally, it includes a presentation layer by using ASP.NET pages, and by using master pages and themes to create a common page layout. This walkthrough shows how to create a data-access layer.

The data-access layer includes all the code that is specific to the underlying data source. This includes code that creates a connection to the database and that issues Select, Insert, Update, and Delete commands. The data-access layer typically contains classes that implement methods for accessing the underlying database data. The presentation layer does not directly work with data. Instead, it invokes classes and methods in the data-access layer for all data requests. You can customize these classes using your own business logic.

Tasks illustrated in this walkthrough include the following:

Creating a SQL database and adding data.

Adding a LINQ to SQL file that acts as the data-access layer.

Creating a page that works as the presentation layer.

Adding a LinqDataSource control to a page that communicates between the presentation layer and the data-access layer.

Prerequisites

To complete the walkthrough, you will need the following:

Visual Studio or Visual Web Developer Express installed on your computer.

If you are using Visual Studio, the walkthrough assumes that you selected the Web Development collection of settings when you started Visual Studio the first time. For more information, see How to: Select Web Development Environment Settings .

SQL Server Express. If you have Microsoft SQL Server installed, you can use that instead.

Creating A Web Site

The first step is to create a Web site.

This walkthrough uses a Web site project. You could use a Web application project instead. For information about the difference between these Web project types, see Web Application Projects versus Web Site Projects .

To create a new file system Web site

Open Visual Studio or Visual Web Developer Express.

In the File menu, click New Web Site .

The New Web Site dialog box is displayed.

Under Installed Templates , click Visual Basic or Visual C# and then select ASP.NET Web Site .

In the Web location box, select File System , and then enter the name of the folder where you want to keep the pages for your Web site.

For example, type the folder name C:\WebSites.

Visual Studio creates a Web site project that includes prebuilt functionality for layout (a master page, the Default.aspx and About.aspx content pages, and a cascading style sheet), for Ajax (client script files), and for authentication (ASP.NET membership).

Connecting to a Database

The next step is to connect to a database in Visual Web Developer by using the Server Explorer window. (In Visual Web Developer Express, the window is named Database Explorer .) Creating a connection to a database in Server Explorer lets you add tables, stored procedures, views, and other database elements, all within Visual Studio. You can also view table data or create queries manually or by using the Query Builder  window.

When you build the typed dataset for the data-access layer later in this walkthrough, you must create a connection in Visual Web Developer to the database. You can provide the connection information manually. However, Visual Web Developer can simplify this process because it automatically populates a list of the databases that are already registered in Server Explorer .

For this walkthrough you will create a new database for tracking task items.

Creating a New SQL Server Express Database

In this section you will create a new SQL Server Express database that will store task information for a to-do list.

To add a database to the Web site

In Solution Explorer , right-click the name of the Web site and then click Add New Item .

The Add New Item window is displayed.

Select SQL Database and name the database Tasks.mdf.

When Visual Web Developer asks you whether the database should be stored in the App_Data folder, click Yes .

Creating a Schema and Sample Data for the Tasks Database

You can use the database design and editing features to create a schema for the table that stores the task items.

To define a schema and add data for the Tasks database

In Solution Explorer , open the App_Data folder and double-click Tasks.mdf.

The Tasks database node is opened in Server Explorer .

Right-click the Tables folder and then click Add New Table .

The table definition window is displayed.

Create the following columns in the table:

Select the row for the taskId column, right-click the row, and then click Set Primary Key .

In the Properties window, set the Identity Column property to the taskId column.

Save the table, name it TasksList, and then close the table-definition window.

Right click the table in Server Explorer and then click Show Table Data .

An editing window is displayed where you can view, add, and edit the data.

Add four or five records to the table.

You do not have to specify a value for the taskId column, because it is an identity column and its value is automatically assigned.

Close the editing window.

Creating the Data Access and Business Logic Layers

You can create a data-access and business-logic layer for the database that you just created in several ways. You can customize these classes using your own business logic.

In this walkthrough, you will create a class that represents database entities. You can then add your own business logic to these generated classes. (You will not add business logic to the classes in this walkthrough.)

In this walkthrough, you will use Language Integrated Query (LINQ) to work with data. LINQ applies the principles of object-oriented programming to relational data. It provides a unified programming model for querying and updating data from different types of data sources and extends data capabilities directly into the C# and Visual Basic languages. For more information about LINQ, see LINQ (Language-Integrated Query) .

You will use LINQ to SQL classes as the data-access layer. You will use the Object Relational Designer window in Visual Web Developer to generate entity classes that represent the data.

Mapping the Tasks Database to a SQL Data Context Class

To begin creating the data-access layer, you add a typed dataset to the project.

To create a class for the Tasks table

If the Web site does not already have an App_Code folder, right-click the project in Solution Explorer , click Add ASP.NET Folder , and then click App_Code .

Right-click the App_Code folder and then click Add New Item .

The Add New Item dialog box is displayed.

Under Visual Studio installed templates , select the LINQ to SQL Classes template and rename the file Tasks.dbml.

Click Add .

The Object Relational Designer window is displayed.

In Server Explorer , drag the TasksList table into the Object Relational Designer window.

Save the Tasks.dbml file.

Visual Web Developer creates the Tasks.dbml.layout file in the App_Code folder under Tasks.dbml. It also creates either Tasks.designer.cs or Tasks.designer.vb, depending on what programming language you are working with.

In Solution Explorer , open the Tasks.designer.cs or Tasks.designer.vb file.

Notice that the code contains classes named TasksDataContext and TasksList. The TasksDataContext class represents the database, and the TasksList class represents the database table. The parameterless constructor for the TasksDataContext class reads the connection string for the database from the Web site's configuration file (Web.config).

Open the Web.config file.

Notice that a connection string to the Tasks database has been added in the connectionStrings element.

Close the class file and the Web.config file.

Creating and Configuring a LinqDataSource Control

Now that you have a database table and classes that represent database entities, you can use a LinqDataSource on an ASP.NET Web page to access the database. The LinqDataSource control makes LINQ available to Web developers through the ASP.NET data-source control architecture.

The LinqDataSource control creates the code for selecting, inserting, updating, and deleting objects in the database. These classes can be called by business logic to perform database functions and apply business-logic rules.

To create and configure a LinqDataSource control

Open or switch to the Default.aspx page.

Switch to Design view.

From the Data tab of the Toolbox , drag a LinqDataSource control onto the Web page.

You can leave the ID property as LinqDataSource1.

In the LinqDataSource Tasks smart tag panel, click Configure Data Source .

In the context object list, select TasksDataContext and then click Next .

In the list, select TasksLists(Table<TasksList>) , and then click Finish .

In the LinqDataSource Tasks smart tag panel, select the Enable Delete , Enable Insert , and Enable Update check boxes.

Save the page.

Notice that you did not have to specify any database commands for selecting the data.

Creating and Configuring a GridView Control

To create a user interface for the data that is made available by the LinqDataSource control, you can use various data controls. In this walkthrough you will add a GridView control to the page in order to view, update, and edit the data in the TasksList table.

To create and configure a GridView control

In the Default.aspx page, switch to Design view.

From the Data tab of the Toolbox , drag a GridView control onto the Web page

In the GridView Tasks smart tag panel, select LinqDataSource1 as the data source. (If you assigned a different name when you created the LinqDataSource control, use that name.)

In the GridView Tasks smart tag panel, select the Enable Editing and Enable Deleting options.

Press CTRL+F5 to run the page.

The page displays the data that you entered previously in the walkthrough, and it enables you to edit or delete rows.

This walkthrough has illustrated how to create the data-access and business-logic layer of an application by using the LINQ to SQL Classes template and the LinqDataSource and GridView server controls. You created a way for Web site pages to access data that is flexible and that is not directly tied to the presentation layer of the Web site.

The topic Walkthrough: Creating an Ajax-Enabled Data Application uses the LinqDataSource control to create an AJAX-enabled Web application that displays and updates information in the Tasks database.

Walkthrough: Creating an Ajax-Enabled Data Application

ASP.NET Walkthroughs by Scenario

Additional resources

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 layer data access layer

:cake :Layered Architecture

Layered Architecture is a software design pattern that is widely used in modern software development. It is a logical and structured approach to software design that separates different functional modules of an application into four separate horizontal layers, each with a specific set of responsibilities. This separation of concerns makes the code more modular, maintainable, and scalable, and enables easier testing and debugging.

This particular architectural pattern has influenced the development of various other architectural patterns, including:

  • Hexagonal Architecture (also known as Ports and Adapters)
  • Onion Architecture
  • Clean Architecture

These patterns have emerged in response to the need to clarify further the concept of layered architecture, and they have each added their own unique features and benefits. However, all these patterns have in common the goal to provide a more modular, flexible, and maintainable approach to building software systems.

Therefore, we strongly recommend understanding the core principles of layered architecture and its relationship to these other patterns, as it will help you better understand these other software architecture patterns, and help you make informed decisions about which approach is best suited to your specific needs and requirements.

In this article, we will focus on the over-arching Layered Architecture , explaining its key principles, benefits, and implementation strategies. We will also discuss some real-world examples of successful implementation and highlight the advantages of using Layered Architecture in modern software development.

What exactly is layered architecture?

Layered architecture is a common pattern used in software design, where the application is divided into different layers based on their functionality. In a four-layered architecture, the layers are typically divided into:

  • Presentation
  • Application
  • Infrastructure

These layers are arranged in a hierarchical order, where each layer provides services to the layer above it and uses services from the layer below it, and each layer is responsible for handling specific tasks and has limited communication with the other layers.

This helps to improve modularity and allows for better separation of concerns. The architecture is called "layered" because it resembles a layered cake, where each layer is independent of the others but builds on them to form a complete and cohesive application.

  • Presentation Layer

The presentation layer is the topmost layer of the architecture, responsible for handling the user interface and displaying data to the user. This layer interacts with the application layer to retrieve the data and provides a visual representation of the data to the user. In web applications, this layer is often implemented using HTML, CSS, and JavaScript.

  • Application Layer

The application layer is responsible for handling business logic and coordinating interactions between different components. This layer receives input from the presentation layer and processes it before passing it down to the domain layer. It is also responsible for communicating with external systems and services. Think of this layer as the maestro in an orchestra, that guides the musicians on what, when and how to play their instrument, but who doesn't actually play any instrument himself. Similarly, the Application Layer doesn't do anything per se, but it tells the domain layer what and when it should do something.

  • Domain Layer

The domain layer contains the business logic and rules of the application. This layer represents the core of the application and defines how the application processes data and interacts with the external world. It is responsible for ensuring the consistency and validity of the data and defines the behavior of the application. Here is where you'll find the algorithms, the programming compoenents, the functions, etc. Its really the heart of the application and generally what adds most value to the application itself.

  • Infrastructure Layer

The infrastructure layer is responsible for handling external dependencies and providing services to the other layers. This layer interacts with databases, file systems, and other external systems. It also provides services such as logging, caching, and authentication to the other layers. By separating infrastructure concerns from the rest of the application, it becomes easier to maintain and replace external dependencies without affecting the core functionality of the application.

  • Advantages of Layered Architecture

Layered architecture offers several advantages that make it a popular choice for large and complex software systems.

Modular structure: By dividing the application into different layers, developers can isolate specific functionalities and easily modify or replace them without affecting other parts of the system. This allows for more agile development and easier maintenance.

Separation of concerns: Each layer is responsible for a specific set of tasks, and there is limited communication between the layers. This helps to ensure that the code is organized and easy to understand, making it easier to test and debug. This ensures a clear separation of the application's functionality and the underlying technology, allowing for better scalability, as additional layers can be added to handle increased functionality without affecting the existing layers.

For example, the presentation layer can be implemented using different technologies, such as a web-based user interface or a mobile app, without affecting the business or data access layers. This flexibility makes it easier to adapt the application to different environments or requirements.
  • Code reusability: Because each layer has a well-defined interface, it is possible to reuse code across different applications or even different layers of the same application. This can save developers time and effort by reducing the amount of code they need to write and maintain.

In large and complex software systems, layered architecture is particularly important. These systems often involve multiple teams of developers working on different parts of the system simultaneously. Layered architecture helps to promote modularity and separation of concerns, making it easier for teams to work independently without stepping on each other's toes. It also makes it easier to manage and maintain the codebase over time, as the structure of the system is well-defined and easy to understand.

Additionally, layered architecture helps to ensure that the system remains robust and reliable. By dividing the application into different layers, developers can focus on specific functionalities and ensure that they are working correctly. This helps to reduce the likelihood of bugs or errors that could cause the system to fail. It also makes it easier to identify and fix issues when they do occur, as the problem is likely to be isolated to a specific layer rather than affecting the entire system.

  • Implementing Layered Architecture

Implementing Layered Architecture involves defining the interfaces and responsibilities of each layer and the interactions between them. Here are some steps to follow when implementing Layered Architecture:

Define the layers: Identify the different layers of the application and their responsibilities. The layers should be as independent as possible, with clear and well-defined interfaces. A good practice is to use a dependency injection framework to manage the dependencies between the layers.

Implement the layers: Develop the classes and functions that implement the functionality of each layer. The classes should only interact with the layer above or below them and should not depend on other layers. Each layer should have its own set of tests to ensure its functionality and integration with the other layers.

Define the interfaces: Define the interfaces between the layers, specifying the methods and parameters that each layer requires from the layer below it. The interfaces should be simple and focused on the specific needs of each layer. The interfaces should be designed to be easy to use, easy to understand, and easy to test.

Handle exceptions: Define how exceptions will be handled between the layers. A good practice is to catch exceptions in the lower layers and convert them to more specific exceptions in the higher layers. This approach helps to keep the application logic separated from the exception handling logic and facilitates debugging.

Test and validate the layers: Once the layers are implemented, test them individually and in combination. Validate that the layers work correctly, that the interfaces are well defined and easy to use, and that the application behaves as expected.

Monitor and maintain the layers: Once the application is in production, monitor and maintain the layers. Ensure that the layers are stable, scalable, and secure. Make any necessary changes to the layers to optimize performance, improve security, or fix bugs.

In summary, implementing a layered architecture is definitely a bit more work than simply not thinking about this, however, its very clear that most developers follow a similar thought process when starting a new project. Therefore, its worth investing just a bit more time into this design process as it will help you build better quality software going forward.

  • Use cases and real-world examples

There are numerous real-world examples of successful implementations of Layered Architecture in various organizations. One such example is the Apache Struts framework, which is widely used for building Java-based web applications. The Struts framework uses a three-layered architecture that separates the presentation, business logic, and data access layers. This has made it easier for developers to maintain and extend the framework, as well as to customize it to meet specific business requirements.

Another example is the Spring framework, which is also widely used for building Java-based web applications. The Spring framework uses a four-layered architecture that includes a presentation layer, a business logic layer, a persistence layer, and a data access layer. This layered approach has made it easier for developers to build scalable, robust, and flexible web applications that can handle large volumes of traffic and complex business logic.

Organizations that have adopted Layered Architecture have benefited from several advantages. Firstly, this approach provides a clear separation of concerns between different layers, which makes it easier to manage complexity and maintainability in larger, more complex software systems. This separation of concerns also allows developers to work more efficiently, as they can focus on specific areas of the application without worrying about the impact on other parts of the system.

Secondly, Layered Architecture enables organizations to achieve better performance and scalability in their software systems. By separating the business logic and data access layers, for example, organizations can optimize each layer for specific performance requirements and improve the overall efficiency of the system.

Lastly, Layered Architecture also supports better reusability and flexibility in software systems. By encapsulating functionality within separate layers, organizations can more easily reuse and extend different components of the system without impacting other parts of the architecture. This can help organizations to build more modular and maintainable software systems that can adapt to changing business requirements over time.

Layered architecture is a fundamental software design pattern that provides a clear separation of concerns and promotes modularity and flexibility in software systems. It allows for the development of robust, scalable, and maintainable applications that can adapt to changing business requirements.

Through understanding the principles and benefits of layered architecture, developers can effectively implement this pattern in their own software projects. With the clear separation of concerns, each layer can be developed and maintained independently, allowing for better code reuse, easier testing, and overall improved software quality.

The importance of using layered architecture in modern software development cannot be overstated. As software systems become increasingly complex, layered architecture provides a scalable and adaptable approach to designing and maintaining such systems. It is a proven methodology that has been successfully implemented in many real-world scenarios.

We encourage developers to start implementing layered architecture in their own software projects. By doing so, they can reap the many benefits that this design pattern has to offer, including improved software quality, easier maintenance, and increased scalability. With careful planning and implementation, layered architecture can be a powerful tool in the development of successful software systems.

  • Additional resources

Here are a few additional references with regards to Layered Architecture:

  • The Layered Architecture Pattern in Software Architecture - Article by Kayvan Kaseb
  • Layered Architecture - Article by Herberto Graça
  • Software Architecture Patterns — Layered Architecture - Article by Priyal Walpita

Flutter App Architecture: The Presentation Layer

Andrea Bizzotto

Andrea Bizzotto

Updated   Sep 21, 2023 11 min read

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

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

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

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

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

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

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

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

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

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

Ready? Let's go!

A simple authentication flow

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

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

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

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

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

The AuthRepository class

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

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

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

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

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

The SignInScreen widget

Suppose we have a simple SignInScreen widget defined like so:

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

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

Accessing the AuthRepository directly from our widget

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

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

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

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

The "StatefulWidget + setState" way

One simple way of addressing this is to:

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

Here's how the resulting code may look like:

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

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

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

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

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

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

A controller class based on AsyncNotifier

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

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

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

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

Implementing the method to sign in

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

A few notes:

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

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

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

Note about the relationship between types

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

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

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

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

Using our controller in the widget class

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

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

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

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

Listening to state changes

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

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

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

Bonus: An AsyncValue extension method

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

To do that, we can define this AsyncValue extension :

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

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

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

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

Meanwhile, the job of our controller is to:

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

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

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

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

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

Flutter Foundations Course Now Available

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

Flutter Foundations Course

Flutter Foundations Course

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

Invest in yourself with my high-quality Flutter courses.

Flutter & Firebase Masterclass

Flutter & Firebase Masterclass

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

The Complete Dart Developer Guide

The Complete Dart Developer Guide

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

Flutter Animations Masterclass

Flutter Animations Masterclass

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

PrepBytes Blog

ONE-STOP RESOURCE FOR EVERYTHING RELATED TO CODING

Sign in to your account

Forgot your password?

Login via OTP

We will send you an one time password on your mobile number

An OTP has been sent to your mobile number please verify it below

Register with PrepBytes

Presentation layer in osi model.

' src=

Last Updated on March 7, 2024 by Abhishek Sharma

presentation layer data access layer

The OSI (Open Systems Interconnection) model is a conceptual framework used to understand the functions of a telecommunication or computing system. It consists of seven layers, each responsible for specific tasks. The sixth layer, known as the Presentation Layer, plays a crucial role in ensuring that data exchanged between systems is readable and usable. Let’s explore the functions and importance of the Presentation Layer in the OSI model.

What is Presentation Layer in OSI Model?

The Presentation Layer, the sixth layer of the OSI (Open Systems Interconnection) model, is responsible for ensuring that data exchanged between systems is in a format that can be interpreted and used by the receiving system. It performs various functions, including data translation, encryption, compression, and formatting, to facilitate efficient and secure communication between networked devices.

Functions of the Presentation Layer

Below are some of the functions of the Presentation Layer in OSI Model:

  • Data Translation: The Presentation Layer translates data from the format used by the application layer into a format that can be transmitted over the network. This includes encoding, compression, and encryption.
  • Data Formatting: It ensures that data is formatted according to the specifications of the application layer. This includes converting between different character sets, such as ASCII and Unicode.
  • Data Compression: The Presentation Layer compresses data to reduce the amount of bandwidth required for transmission, improving network efficiency.
  • Data Encryption: It encrypts data to ensure that it remains secure during transmission, protecting it from unauthorized access.
  • Data Syntax: The Presentation Layer defines the syntax for data representation, ensuring that both the sender and receiver understand the structure of the data being exchanged.

Importance of the Presentation Layer

Importance of Presentation Layer are:

  • Data Integrity: By ensuring that data is formatted correctly and encrypted, the Presentation Layer helps maintain the integrity of data during transmission.
  • Interoperability: The Presentation Layer enables different systems to communicate with each other by ensuring that data is translated into a common format that both systems understand.
  • Efficiency: Data compression reduces the amount of data that needs to be transmitted, improving network efficiency and reducing bandwidth requirements.
  • Security: Encryption provided by the Presentation Layer ensures that data remains secure and protected from unauthorized access.

Conclusion The Presentation Layer is a crucial component of the OSI model, responsible for ensuring that data exchanged between systems is in a format that can be understood and used. By performing functions such as data translation, formatting, compression, and encryption, the Presentation Layer plays a vital role in maintaining data integrity, facilitating interoperability, and ensuring the security of data during transmission.

FAQs related to Presentation Layer in OSI Model

Here are some of the FAQs related to Presentation Layer in OSI Model:

Q1: What is the role of the Presentation Layer in the OSI model? The Presentation Layer ensures that data exchanged between systems is in a usable format, performing functions such as data translation, encryption, compression, and formatting.

Q2: How does the Presentation Layer ensure data security? The Presentation Layer encrypts data before transmission, making it unreadable to unauthorized parties, thus ensuring data security.

Q3: Why is data compression important in the Presentation Layer? Data compression reduces the size of data packets, leading to faster transmission speeds and optimized bandwidth usage, which is crucial in high-traffic networks.

Q4: How does the Presentation Layer facilitate interoperability between systems? By translating data into a common format that both sender and receiver understand, the Presentation Layer enables different systems to communicate with each other seamlessly.

Q5: Can the Presentation Layer be bypassed in data transmission? While it is possible to bypass the Presentation Layer in some cases, doing so can lead to compatibility issues between systems and is not recommended.

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.

  • Linked List
  • Segment Tree
  • Backtracking
  • Dynamic Programming
  • Greedy Algorithm
  • Operating System
  • Company Placement
  • Interview Tips
  • General Interview Questions
  • Data Structure
  • Other Topics
  • Computational Geometry
  • Game Theory

Related Post

Quantum cryptography, introduction to sniffers, multiplexing and demultiplexing in transport layer, transport layer responsibilities, tacacs+ and radius.

The OSI Model – The 7 Layers of Networking Explained in Plain English

Chloe Tucker

This article explains the Open Systems Interconnection (OSI) model and the 7 layers of networking, in plain English.

The OSI model is a conceptual framework that is used to describe how a network functions. In plain English, the OSI model helped standardize the way computer systems send information to each other.

Learning networking is a bit like learning a language - there are lots of standards and then some exceptions. Therefore, it’s important to really understand that the OSI model is not a set of rules. It is a tool for understanding how networks function.

Once you learn the OSI model, you will be able to further understand and appreciate this glorious entity we call the Internet, as well as be able to troubleshoot networking issues with greater fluency and ease.

All hail the Internet!

Prerequisites

You don’t need any prior programming or networking experience to understand this article. However, you will need:

  • Basic familiarity with common networking terms (explained below)
  • A curiosity about how things work :)

Learning Objectives

Over the course of this article, you will learn:

  • What the OSI model is
  • The purpose of each of the 7 layers
  • The problems that can happen at each of the 7 layers
  • The difference between TCP/IP model and the OSI model

Common Networking Terms

Here are some common networking terms that you should be familiar with to get the most out of this article. I’ll use these terms when I talk about OSI layers next.

A node is a physical electronic device hooked up to a network, for example a computer, printer, router, and so on. If set up properly, a node is capable of sending and/or receiving information over a network.

Nodes may be set up adjacent to one other, wherein Node A can connect directly to Node B, or there may be an intermediate node, like a switch or a router, set up between Node A and Node B.

Typically, routers connect networks to the Internet and switches operate within a network to facilitate intra-network communication. Learn more about hub vs. switch vs. router.

Here's an example:

1-Router-Image

For the nitpicky among us (yep, I see you), host is another term that you will encounter in networking. I will define a host as a type of node that requires an IP address. All hosts are nodes, but not all nodes are hosts. Please Tweet angrily at me if you disagree.

Links connect nodes on a network. Links can be wired, like Ethernet, or cable-free, like WiFi.

Links to can either be point-to-point, where Node A is connected to Node B, or multipoint, where Node A is connected to Node B and Node C.

When we’re talking about information being transmitted, this may also be described as a one-to-one vs. a one-to-many relationship.

A protocol is a mutually agreed upon set of rules that allows two nodes on a network to exchange data.

“A protocol defines the rules governing the syntax (what can be communicated), semantics (how it can be communicated), and synchronization (when and at what speed it can be communicated) of the communications procedure. Protocols can be implemented on hardware, software, or a combination of both. Protocols can be created by anyone, but the most widely adopted protocols are based on standards.” - The Illustrated Network.

Both wired and cable-free links can have protocols.

While anyone can create a protocol, the most widely adopted protocols are often based on standards published by Internet organizations such as the Internet Engineering Task Force (IETF).

A network is a general term for a group of computers, printers, or any other device that wants to share data.

Network types include LAN, HAN, CAN, MAN, WAN, BAN, or VPN. Think I’m just randomly rhyming things with the word can ? I can ’t say I am - these are all real network types. Learn more here .

Topology describes how nodes and links fit together in a network configuration, often depicted in a diagram. Here are some common network topology types:

What is Network Topology? Best Guides to Types & Diagrams - DNSstuff

A network consists of nodes, links between nodes, and protocols that govern data transmission between nodes.

At whatever scale and complexity networks get to, you will understand what’s happening in all computer networks by learning the OSI model and 7 layers of networking.

What is the OSI Model?

The OSI model consists of 7 layers of networking.

First, what’s a layer?

Cave, Dragon's Lair, mountains

No, a layer - not a lair . Here there are no dragons.

A layer is a way of categorizing and grouping functionality and behavior on and of a network.

In the OSI model, layers are organized from the most tangible and most physical, to less tangible and less physical but closer to the end user.

Each layer abstracts lower level functionality away until by the time you get to the highest layer. All the details and inner workings of all the other layers are hidden from the end user.

How to remember all the names of the layers? Easy.

  • Please | Physical Layer
  • Do | Data Link Layer
  • Not | Network Layer
  • Tell (the) | Transport Layer
  • Secret | Session Layer
  • Password (to) | Presentation Layer
  • Anyone | Application Layer

Keep in mind that while certain technologies, like protocols, may logically “belong to” one layer more than another, not all technologies fit neatly into a single layer in the OSI model. For example, Ethernet, 802.11 (Wifi) and the Address Resolution Protocol (ARP) procedure operate on >1 layer.

The OSI is a model and a tool, not a set of rules.

OSI Layer 1

Layer 1 is the physical layer . There’s a lot of technology in Layer 1 - everything from physical network devices, cabling, to how the cables hook up to the devices. Plus if we don’t need cables, what the signal type and transmission methods are (for example, wireless broadband).

Instead of listing every type of technology in Layer 1, I’ve created broader categories for these technologies. I encourage readers to learn more about each of these categories:

  • Nodes (devices) and networking hardware components. Devices include hubs, repeaters, routers, computers, printers, and so on. Hardware components that live inside of these devices include antennas, amplifiers, Network Interface Cards (NICs), and more.
  • Device interface mechanics. How and where does a cable connect to a device (cable connector and device socket)? What is the size and shape of the connector, and how many pins does it have? What dictates when a pin is active or inactive?
  • Functional and procedural logic. What is the function of each pin in the connector - send or receive? What procedural logic dictates the sequence of events so a node can start to communicate with another node on Layer 2?
  • Cabling protocols and specifications. Ethernet (CAT), USB, Digital Subscriber Line (DSL) , and more. Specifications include maximum cable length, modulation techniques, radio specifications, line coding, and bits synchronization (more on that below).
  • Cable types. Options include shielded or unshielded twisted pair, untwisted pair, coaxial and so on. Learn more about cable types here .
  • Signal type. Baseband is a single bit stream at a time, like a railway track - one-way only. Broadband consists of multiple bit streams at the same time, like a bi-directional highway.
  • Signal transmission method (may be wired or cable-free). Options include electrical (Ethernet), light (optical networks, fiber optics), radio waves (802.11 WiFi, a/b/g/n/ac/ax variants or Bluetooth). If cable-free, then also consider frequency: 2.5 GHz vs. 5 GHz. If it’s cabled, consider voltage. If cabled and Ethernet, also consider networking standards like 100BASE-T and related standards.

The data unit on Layer 1 is the bit.

A bit the smallest unit of transmittable digital information. Bits are binary, so either a 0 or a 1. Bytes, consisting of 8 bits, are used to represent single characters, like a letter, numeral, or symbol.

Bits are sent to and from hardware devices in accordance with the supported data rate (transmission rate, in number of bits per second or millisecond) and are synchronized so the number of bits sent and received per unit of time remains consistent (this is called bit synchronization). The way bits are transmitted depends on the signal transmission method.

Nodes can send, receive, or send and receive bits. If they can only do one, then the node uses a simplex mode. If they can do both, then the node uses a duplex mode. If a node can send and receive at the same time, it’s full-duplex – if not, it’s just half-duplex.

The original Ethernet was half-duplex. Full-duplex Ethernet is an option now, given the right equipment.

How to Troubleshoot OSI Layer 1 Problems

Here are some Layer 1 problems to watch out for:

  • Defunct cables, for example damaged wires or broken connectors
  • Broken hardware network devices, for example damaged circuits
  • Stuff being unplugged (...we’ve all been there)

If there are issues in Layer 1, anything beyond Layer 1 will not function properly.

Layer 1 contains the infrastructure that makes communication on networks possible.

It defines the electrical, mechanical, procedural, and functional specifications for activating, maintaining, and deactivating physical links between network devices. - Source

Fun fact: deep-sea communications cables transmit data around the world. This map will blow your mind: https://www.submarinecablemap.com/

And because you made it this far, here’s a koala:

Closeup of a Koala

OSI Layer 2

Layer 2 is the data link layer . Layer 2 defines how data is formatted for transmission, how much data can flow between nodes, for how long, and what to do when errors are detected in this flow.

In more official tech terms:

  • Line discipline. Who should talk for how long? How long should nodes be able to transit information for?
  • Flow control. How much data should be transmitted?
  • Error control - detection and correction . All data transmission methods have potential for errors, from electrical spikes to dirty connectors. Once Layer 2 technologies tell network administrators about an issue on Layer 2 or Layer 1, the system administrator can correct for those errors on subsequent layers. Layer 2 is mostly concerned with error detection, not error correction. ( Source )

There are two distinct sublayers within Layer 2:

  • Media Access Control (MAC): the MAC sublayer handles the assignment of a hardware identification number, called a MAC address, that uniquely identifies each device on a network. No two devices should have the same MAC address. The MAC address is assigned at the point of manufacturing. It is automatically recognized by most networks. MAC addresses live on Network Interface Cards (NICs). Switches keep track of all MAC addresses on a network. Learn more about MAC addresses on PC Mag and in this article . Learn more about network switches here .
  • Logical Link Control (LLC): the LLC sublayer handles framing addressing and flow control. The speed depends on the link between nodes, for example Ethernet or Wifi.

The data unit on Layer 2 is a frame .

Each frame contains a frame header, body, and a frame trailer:

  • Header: typically includes MAC addresses for the source and destination nodes.
  • Body: consists of the bits being transmitted.
  • Trailer: includes error detection information. When errors are detected, and depending on the implementation or configuration of a network or protocol, frames may be discarded or the error may be reported up to higher layers for further error correction. Examples of error detection mechanisms: Cyclic Redundancy Check (CRC) and Frame Check Sequence (FCS). Learn more about error detection techniques here .

Example of frames, the network layer, and the physical layer

Typically there is a maximum frame size limit, called an Maximum Transmission Unit, MTU. Jumbo frames exceed the standard MTU, learn more about jumbo frames here .

How to Troubleshoot OSI Layer 2 Problems

Here are some Layer 2 problems to watch out for:

  • All the problems that can occur on Layer 1
  • Unsuccessful connections (sessions) between two nodes
  • Sessions that are successfully established but intermittently fail
  • Frame collisions

The Data Link Layer allows nodes to communicate with each other within a local area network. The foundations of line discipline, flow control, and error control are established in this layer.

OSI Layer 3

Layer 3 is the network layer . This is where we send information between and across networks through the use of routers. Instead of just node-to-node communication, we can now do network-to-network communication.

Routers are the workhorse of Layer 3 - we couldn’t have Layer 3 without them. They move data packets across multiple networks.

Not only do they connect to Internet Service Providers (ISPs) to provide access to the Internet, they also keep track of what’s on its network (remember that switches keep track of all MAC addresses on a network), what other networks it’s connected to, and the different paths for routing data packets across these networks.

Routers store all of this addressing and routing information in routing tables.

Here’s a simple example of a routing table:

A routing table showing the destination, subnet mask, and interface

The data unit on Layer 3 is the data packet . Typically, each data packet contains a frame plus an IP address information wrapper. In other words, frames are encapsulated by Layer 3 addressing information.

The data being transmitted in a packet is also sometimes called the payload . While each packet has everything it needs to get to its destination, whether or not it makes it there is another story.

Layer 3 transmissions are connectionless, or best effort - they don't do anything but send the traffic where it’s supposed to go. More on data transport protocols on Layer 4.

Once a node is connected to the Internet, it is assigned an Internet Protocol (IP) address, which looks either like 172.16. 254.1 (IPv4 address convention) or like 2001:0db8:85a3:0000:0000:8a2e:0370:7334 (IPv6 address convention). Routers use IP addresses in their routing tables.

IP addresses are associated with the physical node’s MAC address via the Address Resolution Protocol (ARP), which resolves MAC addresses with the node’s corresponding IP address.

ARP is conventionally considered part of Layer 2, but since IP addresses don’t exist until Layer 3, it’s also part of Layer 3.

How to Troubleshoot OSI Layer 3 Problems

Here are some Layer 3 problems to watch out for:

  • All the problems that can crop up on previous layers :)
  • Faulty or non-functional router or other node
  • IP address is incorrectly configured

Many answers to Layer 3 questions will require the use of command-line tools like ping , trace , show ip route , or show ip protocols . Learn more about troubleshooting on layer 1-3 here .

The Network Layer allows nodes to connect to the Internet and send information across different networks.

OSI Layer 4

Layer 4 is the transport layer . This where we dive into the nitty gritty specifics of the connection between two nodes and how information is transmitted between them. It builds on the functions of Layer 2 - line discipline, flow control, and error control.

This layer is also responsible for data packet segmentation, or how data packets are broken up and sent over the network.

Unlike the previous layer, Layer 4 also has an understanding of the whole message, not just the contents of each individual data packet. With this understanding, Layer 4 is able to manage network congestion by not sending all the packets at once.

The data units of Layer 4 go by a few names. For TCP, the data unit is a packet. For UDP, a packet is referred to as a datagram. I’ll just use the term data packet here for the sake of simplicity.

Transmission Control Protocol (TCP) and User Datagram Protocol (UDP) are two of the most well-known protocols in Layer 4.

TCP, a connection-oriented protocol, prioritizes data quality over speed.

TCP explicitly establishes a connection with the destination node and requires a handshake between the source and destination nodes when data is transmitted. The handshake confirms that data was received. If the destination node does not receive all of the data, TCP will ask for a retry.

TCP also ensures that packets are delivered or reassembled in the correct order. Learn more about TCP here .

UDP, a connectionless protocol, prioritizes speed over data quality. UDP does not require a handshake, which is why it’s called connectionless.

Because UDP doesn’t have to wait for this acknowledgement, it can send data at a faster rate, but not all of the data may be successfully transmitted and we’d never know.

If information is split up into multiple datagrams, unless those datagrams contain a sequence number, UDP does not ensure that packets are reassembled in the correct order. Learn more about UDP here .

TCP and UDP both send data to specific ports on a network device, which has an IP address. The combination of the IP address and the port number is called a socket.

Learn more about sockets here .

Learn more about the differences and similarities between these two protocols here .

How to Troubleshoot OSI Layer 4 Problems

Here are some Layer 4 problems to watch out for:

  • Blocked ports - check your Access Control Lists (ACL) & firewalls
  • Quality of Service (QoS) settings. QoS is a feature of routers/switches that can prioritize traffic, and they can really muck things up. Learn more about QoS here .

The Transport Layer provides end-to-end transmission of a message by segmenting a message into multiple data packets; the layer supports connection-oriented and connectionless communication.

OSI Layer 5

Layer 5 is the session layer . This layer establishes, maintains, and terminates sessions.

A session is a mutually agreed upon connection that is established between two network applications. Not two nodes! Nope, we’ve moved on from nodes. They were so Layer 4.

Just kidding, we still have nodes, but Layer 5 doesn’t need to retain the concept of a node because that’s been abstracted out (taken care of) by previous layers.

So a session is a connection that is established between two specific end-user applications. There are two important concepts to consider here:

  • Client and server model: the application requesting the information is called the client, and the application that has the requested information is called the server.
  • Request and response model: while a session is being established and during a session, there is a constant back-and-forth of requests for information and responses containing that information or “hey, I don’t have what you’re requesting.”

Sessions may be open for a very short amount of time or a long amount of time. They may fail sometimes, too.

Depending on the protocol in question, various failure resolution processes may kick in. Depending on the applications/protocols/hardware in use, sessions may support simplex, half-duplex, or full-duplex modes.

Examples of protocols on Layer 5 include Network Basic Input Output System (NetBIOS) and Remote Procedure Call Protocol (RPC), and many others.

From here on out (layer 5 and up), networks are focused on ways of making connections to end-user applications and displaying data to the user.

How to Troubleshoot OSI Layer 5 Problems

Here are some Layer 5 problems to watch out for:

  • Servers are unavailable
  • Servers are incorrectly configured, for example Apache or PHP configs
  • Session failure - disconnect, timeout, and so on.

The Session Layer initiates, maintains, and terminates connections between two end-user applications. It responds to requests from the presentation layer and issues requests to the transport layer.

OSI Layer 6

Layer 6 is the presentation layer . This layer is responsible for data formatting, such as character encoding and conversions, and data encryption.

The operating system that hosts the end-user application is typically involved in Layer 6 processes. This functionality is not always implemented in a network protocol.

Layer 6 makes sure that end-user applications operating on Layer 7 can successfully consume data and, of course, eventually display it.

There are three data formatting methods to be aware of:

  • American Standard Code for Information Interchange (ASCII): this 7-bit encoding technique is the most widely used standard for character encoding. One superset is ISO-8859-1, which provides most of the characters necessary for languages spoken in Western Europe.
  • Extended Binary-Coded Decimal Interchange Code (EBDCIC): designed by IBM for mainframe usage. This encoding is incompatible with other character encoding methods.
  • Unicode: character encodings can be done with 32-, 16-, or 8-bit characters and attempts to accommodate every known, written alphabet.

Learn more about character encoding methods in this article , and also here .

Encryption: SSL or TLS encryption protocols live on Layer 6. These encryption protocols help ensure that transmitted data is less vulnerable to malicious actors by providing authentication and data encryption for nodes operating on a network. TLS is the successor to SSL.

How to Troubleshoot OSI Layer 6 Problems

Here are some Layer 6 problems to watch out for:

  • Non-existent or corrupted drivers
  • Incorrect OS user access level

The Presentation Layer formats and encrypts data.

OSI Layer 7

Layer 7 is the application layer .

True to its name, this is the layer that is ultimately responsible for supporting services used by end-user applications. Applications include software programs that are installed on the operating system, like Internet browsers (for example, Firefox) or word processing programs (for example, Microsoft Word).

Applications can perform specialized network functions under the hood and require specialized services that fall under the umbrella of Layer 7.

Electronic mail programs, for example, are specifically created to run over a network and utilize networking functionality, such as email protocols, which fall under Layer 7.

Applications will also control end-user interaction, such as security checks (for example, MFA), identification of two participants, initiation of an exchange of information, and so on.

Protocols that operate on this level include File Transfer Protocol (FTP), Secure Shell (SSH), Simple Mail Transfer Protocol (SMTP), Internet Message Access Protocol (IMAP), Domain Name Service (DNS), and Hypertext Transfer Protocol (HTTP).

While each of these protocols serve different functions and operate differently, on a high level they all facilitate the communication of information. ( Source )

How to Troubleshoot OSI Layer 7 Problems

Here are some Layer 7 problems to watch out for:

  • All issues on previous layers
  • Incorrectly configured software applications
  • User error (... we’ve all been there)

The Application Layer owns the services and functions that end-user applications need to work. It does not include the applications themselves.

Our Layer 1 koala is all grown up.

Koala with Photoshopped makeup

Learning check - can you apply makeup to a koala?

Don’t have a koala?

Well - answer these questions instead. It’s the next best thing, I promise.

  • What is the OSI model?
  • What are each of the layers?
  • How could I use this information to troubleshoot networking issues?

Congratulations - you’ve taken one step farther to understanding the glorious entity we call the Internet.

Learning Resources

Many, very smart people have written entire books about the OSI model or entire books about specific layers. I encourage readers to check out any O’Reilly-published books about the subject or about network engineering in general.

Here are some resources I used when writing this article:

  • The Illustrated Network, 2nd Edition
  • Protocol Data Unit (PDU): https://www.geeksforgeeks.org/difference-between-segments-packets-and-frames/
  • Troubleshooting Along the OSI Model: https://www.pearsonitcertification.com/articles/article.aspx?p=1730891
  • The OSI Model Demystified: https://www.youtube.com/watch?v=HEEnLZV2wGI
  • OSI Model for Dummies: https://www.dummies.com/programming/networking/layers-in-the-osi-model-of-a-computer-network/

Chloe Tucker is an artist and computer science enthusiast based in Portland, Oregon. As a former educator, she's continuously searching for the intersection of learning and teaching, or technology and art. Reach out to her on Twitter @_chloetucker and check out her website at chloe.dev .

Read more posts .

If you read this far, thank the author to show them you care. Say Thanks

Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

  • Web Application Development Enterprise applications maximize your efficiency
  • Flutter App Development Building the next-gen mobile app that rocks
  • Software Customization & Enhancement Make your existing software better
  • Real Estate
  • Construction
  • Marketplace
  • Data Management
  • Procurement
  • Recruitment
  • Microservices
  • Schedule a Call

Diving deep into the ocean of technology

How to build and deploy a three-layer architecture application with C#

  • February 27, 2021 • Development

What’s three-layer architecture?

Layer indicates the logical separation of components. Layered architecture concentrates on grouping related functionality within an application into distinct layers that are stacked vertically on top of each other. Each layer has unique namespaces and classes.

An N-layer application may reside on the same physical computer (same tier); each layer's components communicate with another layer’s components by well-defined interfaces.

In C#, each layer is often implemented in a Dynamic Link Libraries (DLL) file.

To help you understand more about the n-layer architecture, I’ve put together all pieces of information about three-layer with a practical example in this article as follows:

  • Presentation layer It is the first and topmost layer present in the application where users can interact with the application.
  • Business Logic layer This is the middle layer - the heart of the application. It contains all business logic of the application, describes how business objects interact with each other, where the Presentation layer and Data Access layer can indirectly communicate with each other.
  • Data Access layer The Data Access layer enforces rules regarding accessing data, providing simplified access to data stored in persistent storage, such as SQL Server. It is noteworthy that this layer only focuses on data access instead of data storage. It may create a bit of confusion with the Data-tier in a three-tier architecture.

Advantages of three-layer architecture

  • Explicit code: The code is separated into each layer. Each one is dedicated to a single responsibility such as interface, business processing, and querying instead of bundling all the code in one place.
  • Easy to maintain: As its roles separate each layer, it would be easier to change something. The modification can be isolated in a single layer or affected only the nearest layer without affecting the whole program.
  • Easy to develop, reuse: When we want to modify a function, we can easily do that as we already have a standard architecture. In case we want to alter a complete layer such as from Winform to Web form, we only need to implement to replace the Presentation layer; other layers can be reused completely.
  • Easy to transfer: We could save time on moving the application to others as they have a standard architecture to follow and apply.
  • Easy to distribute the workloads: By organizing the code into different layers based on its responsibility, each team/member can write their code on each layer independently, which in turn helps developers control their workload.

How does it work?

In three-layer architecture, the Presentation layer doesn’t communicate directly with the Data Access layer. The Business Logic layer works as a bridge between the Presentation layer and the Data Access layer. The three-layer architecture works as follows:

  • The Presentation layer is the only class that is directly interacted with the user. It is mainly used for presenting/collecting data from users, then passes them to the Business Logic layer for further processing.
  • After receiving information from the Presentation layer, the Business Logic layer does some business logic on the data. During this process, this layer may retrieve or update some data from the application database. However, this layer doesn’t take responsibility for accessing the database; it sends requests to the next layer, the Data Access layer.
  • The Data Access layer receives requests from the Business Logic layer and builds some queries to the database to handle these requests. Once the execution gets done, it sends the result back to the Business Logic layer.
  • The Business Logic layer gets responses from the Data Access layer, then completes the process and sends the result to the Presentation Layer.
  • The Presentation layer gets the responses and presents them to users via UI components.

The diagram below illustrates how three-layer architecture works.

How to build and deploy 3-layer architecture application with C#

How to build and deploy a three-layer application in C#?

To guide you build and deploy a three-layer application, I have prepared a demo with the following components:

  • Business Objects - Entity(Data Transfer Objects) layer: .NET Core class library
  • Data Access layer: .NET Core class library
  • Business Logic layer: .NET Core class library
  • Presentation Layer: ASP.NET Core 5.0 Razor pages

The Business Objects layer includes objects that are used in the application and common helper functions (without logic) used for all layers. In a three-layer architecture, this layer is optional. However, as we follow the OOP with C#, we should reduce the duplicate codes as much as possible. Therefore, using a layer to keep common codes instead of holding them in each layer is essential.

To easily follow the article, you can download the demo of the three-layer architecture sample . It is built based on Repository + UnitOfWork pattern, which’s a well-designed pattern in C#. Here are the demo and practical examples of the Repository + UnitOfWork pattern .

The diagram below explains how the application was designed.

How is a 3-layer application designed?

Firstly, create a database with the design below to store the application’s data. You can execute the ThreeLayerSample.Database.sql, which was placed inside the Data Access layer to create it.

3-layer database

The demo will focus on getting the Work table items before representing them to users.

Business Objects/Entity layer

ThreeLayerSample.Domain class project in this example.

1. Connect to the database with Entity Framework Core

When we have the database, we need to create a mapping between the database and the application. Let’s open your Package Manager console in this layer, run a Scaffolding command, then replace SERVER, DATABASE, USER, and PASSWORD with suitable values based on your SQL Server settings.

Once the command has finished, the database tables should be created into the code and name entities. As the entities could be used in all layers without any database or business logic, we should keep them in this layer.

3-layer sample

A DataContext class named “DemoContext” is also created. This class provides database access, so it should be placed in the Data Access layer.

democontext

2. Create Generic interfaces for Repository and UnitOfWork

All data entities should have CRUD actions, so let’s create a generic interface named IRepository, and then the repository of each entity should implement this interface.

ThreeLayerDomain/Interfaces/IRepository.cs

We need another interface named IUnitOfWork as follows:

ThreeLayerDomain/Interfaces/IUnitOfWork.cs

They are interfaces without business/database logic here, so I put them in this layer.

Data Access layer

ThreeLayerSample.Infrastructure class project in this example.

1. Implement generic classes

By applying Generic Repository and Unit of Work design patterns, the data access layer classes are implemented as follows:

ThreeLayerSample.Infrastructure/Repository.cs

ThreeLayerSample.Infrastructure/UnitOfWork.cs

And another DbFactory class that will initialize a DbContext when we use it.

ThreeLayerSample.Infrastructure/DbFactory.cs

Business Logic layer

ThreeLayerSample.Service class project in this example.

1. Create an interface for the service

Let’s create the interface for the WorkService that the Presentation layer depends on as we don’t want to tighten the Presentation layer and Business Logic layer with a concrete implementation.

ThreeLayerSample.Domain/Interfaces/Services/IWorkService.cs

2. Implement code for the service

Next, implement business logic processing the Work service in a class named WorkService as follows. This is the business logic processing code, so we put this class in the Business Logic layer. As you can see, the service requests to get all items of the Work table via the Repository instance of the Work entity, which was implemented in the generic repository.

ThreeLayerSample.Service/WorkService.cs

Presentation layer

ThreeLayerSample.Web(Razor) ASP.NET Core Web App in this example.

Follow this tutorial to create an ASP.NET Core Razor page application . Once the application is created, create a ServiceCollectionExtensions class under the Extensions folder.

ThreeLayerSample.Web_Razor_/Extensions/ServiceCollectionExtensions .cs

Add your connection string into the appsettings.json file, and it’s the connection string that the Data Access layer will employ to establish a connection to the database (same value as the connection string in the Scaffold command).

ThreeLayerSample.Web_Razor_/appsettings.json

Add an AppSettings class to the Entity layer.

ThreeLayerSample.Domain/Models/AppSettings.cs

Open the Startup.cs file, then add the following codes.

At its constructor: read data from appsettings.json, then store it in the created AppSettings class.

In the ConfigureServices: register instances for DataContext, its Factory, UnitOfWork, and WorkService to the application (using extension methods in ServiceCollectionExtensions class).

ThreeLayerSample.Web_Razor_/Startup.cs

Open Index.cshtml.cs file, add the following code to inject WorkService, then get data from WorkService and set it to Works property.

ThreeLayerSample.Web_Razor_/Pages/Index.cshtml.cs

In the Index.cshtml file, add the following code to present data to the UI.

ThreeLayerSample.Web_Razor_/Pages/Index.cshtml.

Run the application to check for the result.

Testing 3-layer

Create a folder to store your source code.

deployment 3-layer

Open your IIS, then choose Create Website to host your application. Provide a name, a specific port, and a physical path to the source code folder for the Content Directory section. Make sure “Start website immediately” is ticked.

3-layer deployment 2

Open your solution in your Visual Studio, then follow these steps:

Right-click on ThreeLayerSample.Web(Razor), select Publish.

publish 3-layer

Select “Folder”.

Publish a 3-layer architecture application

Enter “Folder location” by creating the source code folder path below.

publish location

Click to publish the project.

Publish

Once you’ve done publishing, open the application on your browser to check for the result.

Publish a 3-layer architecture application

The layered architecture is well-designed for software development that helps organize your code with high maintainability, reusability, and readability. However, even though codes are well-organized in layers, they are deployed and run on the same physical machine, even on the same process. This may not be the right choice for complex applications, which require high availability and stability. We need to upgrade this architecture to another higher level named three-tier architecture, which I will share in my next article.

Thank you for reading, and happy coding!

CTA Enlab Software

  • Loc Nguyen, How to implement Repository & Unit of Work design patterns in .NET Core with practical examples [Part 1] , enlabsoftware.com/, 2021.
  • Anant Patil, Three Layered Architecture , www.ecanarys.com.
  • Mark Richards, Software Architecture Patterns , www.oreilly.com.

Uyen Luu

About the author

Uyen Luu

Can we send you our next blog posts? Only the best stuffs.

How-To Geek

The 7 osi networking layers explained.

The Open Systems Interconnection (OSI) networking model defines a conceptual framework for communications between computer systems.

Quick Links

  • Physical Layer
  • Data Link Layer
  • Network Layer
  • Transport Layer
  • Session Layer
  • Presentation Layer
  • Application Layer

The Open Systems Interconnection (OSI) networking model defines a conceptual framework for communications between computer systems. The model is an ISO standard which identifies seven fundamental networking layers, from the physical hardware up to high-level software applications.

Each layer in the model handles a specific networking function. The standard helps administrators to visualize networks, isolate problems, and understand the use cases for new technologies. Many network equipment vendors advertise the OSI layer that their products are designed to slot into.

OSI was adopted as an international standard in 1984. It remains relevant today despite the changes to network implementation that have occurred since first publication. Cloud, edge, and IoT can all be accommodated within the model.

In this article, we'll explain each of the seven OSI layers in turn. We'll start from the lowest level, labelled as Layer 1.

1. Physical Layer

All networking begins with physical equipment. This layer encapsulates the hardware involved in the communications, such as switches and cables. Data is transferred as a stream of binary digits - 0 or 1 - that the hardware prepares from input it's been fed. The physical layer specifies the electrical signals that are used to encode the data over the wire, such as a 5-volt pulse to indicate a binary "1."

Errors in the physical layer tend to result in data not being transferred at all. There could be a break in the connection due to a missing plug or incorrect power supply. Problems can also arise when two components disagree on the physical encoding of data values. In the case of wireless connections, a weak signal can lead to bit loss during transmission.

2. Data Link Layer

The model's second layer concerns communication between two devices that are directly connected to each other in the same network. It's responsible for establishing a link that allows data to be exchanged using an agreed protocol. Many network switches operate at Layer 2.

The data link layer will eventually pass bits to the physical layer. As it sits above the hardware, the data link layer can perform basic error detection and correction in response to physical transfer issues. There are two sub-layers that define these responsibilities: Logical Link Control (LLC) that handles frame synchronization and error detection, and Media Access Control (MAC) which uses MAC addresses to constrain how devices acquire permission to transfer data.

3. Network Layer

The network layer is the first level to support data transfer between two separately maintained networks. It's redundant in situations where all your devices exist on the same network.

Data that comes to the network layer from higher levels is first broken up into packets suitable for transmission. Packets received from the remote network in response are reassembled into usable data.

The network layer is where several important protocols are first encountered. These include IP (for determining the path to a destination), ICMP, routing, and virtual LAN. Together these mechanisms facilitate inter-network communications with a familiar degree of usability. However operations at this level aren't necessarily reliable: messages aren't required to succeed and may not necessarily be retried.

4. Transport Layer

The transport layer provides higher-level abstractions for coordinating data transfers between devices. Transport controllers determine where data will be sent and the rate it should be transferred at.

Layer 4 is where TCP and UDP are implemented, providing the port numbers that allow devices to expose multiple communication channels. Load balancing is often situated at Layer 4 as a result, allowing traffic to be routed between ports on a target device.

Transport mechanisms are expected to guarantee successful communication. Stringent error controls are applied to recover from packet loss and retry failed transfers. Flow control is enforced so the sender doesn't overwhelm the remote device by sending data more quickly than the available bandwidth permits.

5. Session Layer

Layer 5 creates ongoing communication sessions between two devices. Sessions are used to negotiate new connections, agree on their duration, and gracefully close down the connection once the data exchange is complete. This layer ensures that sessions remain open long enough to transfer all the data that's being sent.

Checkpoint control is another responsibility that's held by Layer 5. Sessions can define checkpoints to facilitate progress updates and resumable transmissions. A new checkpoint could be set every few megabytes for a file upload, allowing the sender to continue from a particular point if the transfer gets interrupted.

Many significant protocols operate at Layer 5 including authentication and logon technologies such as LDAP and NetBIOS. These establish semi-permanent communication channels for managing an end user session on a specific device.

6. Presentation Layer

The presentation layer handles preparation of data for the application layer that comes next in the model. After data has made it up from the hardware, through the data link, and across the transport, it's almost ready to be consumed by high-level components. The presentation layer completes the process by performing any formatting tasks that may be required.

Decryption, decoding, and decompression are three common operations found at this level. The presentation layer processes received data into formats that can be eventually utilized by a client application. Similarly, outward-bound data is reformatted into compressed and encrypted structures that are suitable for network transmission.

TLS is one major technology that's part of the presentation layer. Certificate verification and data decryption is handled before requests reach the network client, allowing information to be consumed with confidence that it's authentic.

7. Application Layer

The application layer is the top of the stack. It represents the functionality that's perceived by network end users. Applications in the OSI model provide a convenient end-to-end interface to facilitate complete data transfers, without making you think about hardware, data links, sessions, and compression.

Despite its name, this layer doesn't relate to client-side software such as your web browser or email client. An application in OSI terms is a protocol that caters for the complete communication of complex data through layers 1-6.

HTTP, FTP, DHCP, DNS, and SSH all exist at the application layer. These are high-level mechanisms which permit direct transfers of user data between an origin device and a remote server. You only need minimal knowledge of the workings of the other layers.

The seven OSI layers describe the transfer of data through computer networks. Understanding the functions and responsibilities of each layer can help you identify the source of problems and assess the intended use case for new components.

OSI is an abstract model that doesn't directly map to the specific networking implementations commonly used today. As an example, the TCP/IP protocol works on its own simpler system of four layers: Network Access, Internet, Transport, and Application. These abstract and absorb the equivalent OSI layers: the application layer spans OSI L5 to L7, while L1 and L2 are combined in TCP/IP's concept of Network Access.

OSI remains applicable despite its lack of direct real-world application. It's been around so long that it's widely understood among administrators from all backgrounds. Its relatively high level of abstraction has also ensured it's remained relevant in the face of new networking paradigms, many of which have targeted Layer 3 and above. An awareness of the seven layers and their responsibilities can still help you appreciate the flow of data through a network while uncovering integration opportunities for new components.

presentation layer data access 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
  • What is Software RAID?
  • What is Report Generator?
  • Predicate Locking
  • Hardware RAID
  • Audit Trail
  • Measures of Query Cost in DBMS
  • Virtual Private Database (VPD)
  • What is EII(Enterprise Information Integration)?
  • Business-Logic Layer
  • Introduction to NoSQL Cloud Database Services
  • Query-Execution Plan in SQL
  • Strategies For Migrating From SQL to NoSQL Database
  • What is Data Inconsistency in DBMS?
  • ODBS Full Form
  • Weak Levels of Consistency
  • Access Types in DBMS
  • Difference Between Hardware RAID vs Software RAID
  • Double Buffering
  • Difference Between Data Mining and Data Analysis

Data-Access Layer

In this article, we are going to learn about the Business Logic Layer in Database Management systems . A DBMS usually consists of various layers where each one has a specific kind of task it performs. The main purpose of the layered structure is to implement abstraction in Database systems. Change in one schema must not affect the other schema. This architecture allows the Database Administrator to design the schema and implement methods to allow secured access to the stored data.

The Data-Access Layer (DAL) is a component of a software architecture that is responsible for managing the data storage and retrieval of an application. It sits between the business-logic layer and the data storage system and provides an abstraction layer that allows the business-logic layer to interact with the data storage system without being aware of its specific implementation.

The DAL is responsible for performing tasks such as: -Connecting to the data storage system and managing the connection. -Generating and executing SQL queries or other data access commands to retrieve and store data. -Mapping the data from the data storage system to the application’s data objects and vice versa. -Handling errors and exceptions related to data access. -Providing support for transactions and other data access features.

The DAL is designed to be reusable and independent of the business logic and data storage implementation. This allows the application to be easily modified or extended without affecting the underlying data access code.

The DAL can be implemented using different data access technologies, such as ADO.NET, JDBC, or ORM (Object-relational mapping) libraries. The choice of technology will depend on the specific requirements of the application and the data storage system being used.

In summary, The Data-Access Layer (DAL) is a component of a software architecture that is responsible for managing the data storage and retrieval of an application. It sits between the business-logic layer and the data storage system and provides an abstraction layer that allows the business-logic layer to interact with the data storage system without being aware of its specific implementation. The DAL is designed to be reusable and independent of the business logic and data storage implementation. It can be implemented using different data access technologies and it provides support for transactions and other data access features.

Data-Access Layer (DAL)  

Data-Access Layer is a layer in an application that provides easy and simplified access to data stored in persistent storage, such as an entity-relational database or any database for that matter. It is layer that exists between the Business Logic Layer (BLL) and the storage layer . 

Let us understand some terminologies involved: 

1. Data-Access Object (DAO): They are entities that are collectively known as the Data Access Layer (DAL). A DAL might be a single class, or it might be composed of multiple Data Access Objects (DAOs). 

2. Business Logic Layer: The business logic layer consists of all the objects and functionalities which handle the business logic of the application, this is where the main implementation of an application takes place and it is very unique for each application. 

3. Storage Layer: The actual database where data is stored, upon which CRUD operations can be performed. This might be some remote or cloud storage.

Data Access Layer

Data Access Layer

Whenever a specific data query or update is required by the Application (BLL), the request is sent to the Data Access Layer, which then takes appropriate actions to ensure that the requested data or updation is performed, this results in a level of abstraction wherein the Business Layer will only know which function or methods to call, and it does not have to know the actual architecture or details of the entire Database.  

Purpose/Importance of having a DAL:

  • Provides a centralized location from where calls are made onto the database(s).
  • Provides a layer of abstraction as a developer working on the Business Logic need not worry about the way in which data is stored or their CRUD operations.
  • A Data-Access Layer (DAL) can support multiple databases, so the application is able to make use of any database as per its requirement.
  • Because segregating the data access code, enables better maintainability and easy migration of the database.

Example : 

Let us assume an airline ticket reservation system, when a user attempts to view the flight availability from the front-end, the business logic layer will send the query request to the Data-Access Layer, from here its this layer’s job to interact with the storage and obtain the queried results. The Business logic layer is not concerned with the way in which data is represented in the storage, whether it is relational or non-relational types. It is the job of the DAL to retrieve the required data from one or more locations from the storage(s) and send it back to the Business Logic Layer, which is converted to user-understandable format, then sent to the front-end.

Please Login to comment...

Similar reads.

  • Computer Subject

advertisewithusBannerImg

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

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. Creating a Data Access Layer (C#)

    Step 1: Creating a Web Project and Connecting to the Database. Before we can create our Data Access Layer (DAL), we first need to create a web site and setup our database. Start by creating a new file system-based ASP.NET web site. To accomplish this, go to the File menu and choose New Web Site, displaying the New Web Site dialog box.

  3. Three Tier Architecture In ASP.NET Core 6 Web API

    Steps to follow for configuring these layers, Add the Class Library project of Asp.net for Data Access Layer. Right Click on the project and then go to the add the new project window and then add the Asp.net Core class library project. After Adding the Data Access layer project now, we will add the Business access layer folder.

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

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

  6. Understanding Layered Architecture: A Comprehensive Guide

    Data Access Layer: Manages data storage, retrieval, and communication with databases. 2. Dependencies: ... Presentation Layer: Handles user interactions through a web interface.

  7. Data Access Layer Explained

    Data Access Layer. Generally, we can perceive the Data Access Layer (DAL) as a gateway for the database. An application receives input from the Presentation Layer (PL) and processes it in the Business Logic Layer (BLL). The job of the DAL is to thoroughly validate the semantics and authorization and retrieve data from storage.

  8. Presentation layer

    The presentation layer ensures the information that the application layer of one system sends out is readable by the application layer of another system. On the sending system it is responsible for conversion to standard, transmittable formats. [7] On the receiving system it is responsible for the translation, formatting, and delivery of ...

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

  10. Presentation Layer

    The presentation layer is the lowest layer at which application programmers consider data structure and presentation, instead of simply sending data in the form of datagrams or packets between hosts. This layer deals with issues of string representation - whether they use the Pascal method (an integer length field followed by the specified ...

  11. The Three Layered Architecture. Layers

    The presentation layer is the highest layer of the software. It is where the user interface of the software is placed. ... Data Access Layer (DAL) This layer is separated into two: DAL ...

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

    The recommended approach is to separate the data access logic from the presentation layer. This separate layer is referred to as the data-access layer. The data-access layer can be implemented as a separate Class Library project. However, you can also use tools in Visual Web Developer that can generate a data-access layer for you.

  13. 1. Layered Architecture

    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. ... The data access objects illustrated in the ...

  14. What is presentation layer?

    The presentation layer is located at Layer 6 of the OSI model. The tool that manages Hypertext Transfer Protocol ( HTTP) is an example of a program that loosely adheres to the presentation layer of OSI. Although it's technically considered an application-layer protocol per the TCP/IP model, HTTP includes presentation layer services within it.

  15. Layered Architecture: Building Scalable & Maintainable Software Systems

    The Spring framework uses a four-layered architecture that includes a presentation layer, a business logic layer, a persistence layer, and a data access layer. This layered approach has made it easier for developers to build scalable, robust, and flexible web applications that can handle large volumes of traffic and complex business logic.

  16. Flutter App Architecture: The Presentation Layer

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

  17. Presentation Layer in OSI Model

    The Presentation Layer is a crucial component of the OSI model, responsible for ensuring that data exchanged between systems is in a format that can be understood and used. By performing functions such as data translation, formatting, compression, and encryption, the Presentation Layer plays a vital role in maintaining data integrity ...

  18. The OSI Model

    Incorrect OS user access level; TL;DR. The Presentation Layer formats and encrypts data. OSI Layer 7. Layer 7 is the application layer. True to its name, this is the layer that is ultimately responsible for supporting services used by end-user applications.

  19. How to build and deploy a three-layer architecture ...

    The Business Logic layer works as a bridge between the Presentation layer and the Data Access layer. The three-layer architecture works as follows: The Presentation layer is the only class that is directly interacted with the user. It is mainly used for presenting/collecting data from users, then passes them to the Business Logic layer for ...

  20. The 7 OSI Networking Layers Explained

    Data Link Layer. Network Layer. Transport Layer. Session Layer. Presentation Layer. Application Layer. Summary. The Open Systems Interconnection (OSI) networking model defines a conceptual framework for communications between computer systems. The model is an ISO standard which identifies seven fundamental networking layers, from the physical ...

  21. 3 Layered Architecture

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

  22. Data-Access Layer

    The Data-Access Layer (DAL) is a component of a software architecture that is responsible for managing the data storage and retrieval of an application. It sits between the business-logic layer and the data storage system and provides an abstraction layer that allows the business-logic layer to interact with the data storage system without ...

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

  24. Understanding the Layers of Database Management Systems

    External Layer. The external level, also known as the user interface layer, is the topmost tier in the three-tier architecture of a database management system (DBMS). It serves as the gateway for end-users to interact with the system, presenting data in a format that is understandable and accessible to them. This layer encapsulates user-facing ...