Image

What if your problem is simple and time is of the essence? Should you even bother with architecture? It depends on how long you want to keep what you build. If it’s disposable, throw caution to the wind. If not, then choose the simplest architecture that still provides some measurable organization and benefit, without imposing many constraints on speed of delivery. The layered architecture has become that architecture because it’s easy to understand and implement, leveraging design patterns developers already know. Let’s peel back the layers of this architecture.

Naan & Pop: Gathering requirements

Sangita likes simple meals, so she created an Indian-inspired mom-and-pop restaurant called Naan & Pop, specializing in flatbread sandwiches and sodas.

The restaurant needs a website where customers can place orders online. Since Naan & Pop is a startup with a small budget, it needs to be simple and created quickly.

Sangita has some specific requirements.

Image

Time to market

The restaurant is already open. The faster they can get the site online, the faster they can start making money. The site should be simple.

Image

Separation of responsibilities

The company has part-time help with specialized skills, such as user interface (UI) specialists and database administrators (DBAs). Thus, it would help to keep each part of the system separate.

Image

Simple, yet extensible

While this is Sangita’s first foray into software architecture, she would like to keep building on the company’s online presence and find ways to extend and reuse parts of the system.

Image

Sangita has some software development experience and realizes that many of these goals require a good separation of responsibilities. She passes these requirements to the development team she’s hired for this project. You’re a part of that team, so pay close attention.

Cubicle conversation

Image

Alex: Our project manager just sent the requirements and goals for Naan & Pop’s web application. It’s so simple. Couldn’t we just find an existing framework or library to handle most of it?

Mara: That would solve the simplicity goal. But Sangita also wants extensibility, and existing frameworks tend to be a bit rigid.

Sam: What kind of extensibility does she want?

Mara: If the restaurant is a success, we might want the site to support different kinds of user interfaces, or we could build integration points for delivery services.

Alex : Yeah—existing simple applications might not handle the separation of responsibilities Sangita would need for that kind of extensibility.

Sam: But we don’t have time to build a fancy architecture!

Alex: This seems impossible—how can we build a proper architecture with specializations under these time constraints?

Sam: Fortunately, we’ve already worked with other team members to define the architectural characteristics (for the application’s capabilities) and domain design (for its behavior). We just need to choose the appropriate architecture.

Mara: Those are some serious trade-offs and conflicting goals. We need a simple architectural style that lets us separate responsibilities around technical areas, such as user interface, data, business logic, and so on. That way, adding a new user interface will only affect one layer.

Alex: “Separate responsibilities...” I just read that phrase in the book Head First Design Patterns ! I was reading about the Model-View-Controller design pattern.

Sam: Yeah, but that’s a design pattern—how would you translate that to architecture?

Mara: Lots of design patterns end up in architecture, because often their goals overlap. But, while design patterns can focus just on design elements, architecture has to account for real-world constraints. Let’s crack open the book and see if we can map Model-View-Controller into architecture.

Design patterns redux

To illustrate the concept of design patterns, the influential book Head First Design Patterns uses the Model-View-Controller (MVC) design pattern, which separates capabilities based on their purpose.

Note

A “design pattern” is a contextualized solution to a common problem in software design.

Image

In MVC, the model represents business logic and entities in the application; the view represents the user interface; and the controller handles the workflow, stitching model elements together to provide the application’s functionality, as shown here:

Image

Brain Power

Image

The MVC design pattern separates logical responsibilities, but software architecture must also deal with physical systems, like browsers and databases. How would you split the responsibilities covered by MVC within the constraints of software architecture, while maintaining the overall goal of separating responsibilities and concerns?

Layering MVC

Design patterns represent logical solutions to problems, but architecture must deal with real-world constraints like databases, user interfaces, and other implementation details.

Image

Today’s lnterview

Image

Layering it on with an architecture star: the Layer

Head First: Welcome, Layer, to our luxurious studio. I know you have a busy schedule, so thanks for making the time.

Layer: You’re welcome. As you say, I’m a pretty big deal. They even named an architecture after me!

Head First: Let’s dig into that, Layer. Why base a whole architecture on you?

Layer: Great question. I make everything nice and understandable in an application’s architecture, since each layer has a specific responsibility.

Head First: So, this architecture is just for neat freaks?

Layer: No! Putting all the similar functionality in separate layers makes it easier to find it again to make changes. For example, if the team needs to add a different database, they only have to change the persistence layer.

Head First: Ah. So organizing everything allows for easier discovery and updating. Seems like a good reason for an architecture.

Layer: While unified organization is nice, it’s not the only reason to base an architecture on me.

Head First: What do you mean?

Layer: I hate to brag, but us layers are quite flexible—we can be used for all sorts of things!

Head First: Well, I know you often show up for user interfaces and provide a place to put all the business logic.

Layer: Sure, we do the heavy lifting for those. But teams can mold us into all kinds of UIs. For instance, a services layer can provide an interface to other applications that need to interact with this one.

Head First: Do you have a good example of how teams have leveraged you, Layer?

Layer: You bet! I worked with a team that handled loyalty programs for a hotel. Every purchase a user made could qualify for bonus points, depending on their membership status, years of membership, and a bunch of other complicated stuff. The team successfully used a bonus layer to keep all the calculations in a single place.

Head First: OK, that sounds useful. Can you address the recent controversy about your chilly relationship with Domain-Driven Design?

Layer: What kind of interview is this? There’s no credence to those rumors that we can’t get along. Well, as you know, I specialize in technical separation. My friend DDD focuses more on domain or business separation. I’m happy to host a domain in my architecture, but it’ll likely have to split across the layers.

Head First: Isn’t it true that you’re older than other architectural styles?

Layer: The idea of layers in architecture predates just about any other concept. And is that really surprising? When architects start thinking about how to organize things, I just make sense.

Head First: We’re nearly out of time, but can you tell us about your cozy relationship with the monolith? You seem to be hosted by it a lot.

Layer: No comment.

Image

Great question. Requests and responses flow through the layers.

In a layered monolithic architecture, when a user asks the system to do something, the user interface initiates the request. Then that request flows through each layer in the architecture. If the database is involved in persisting something, then the request goes from top to bottom and back.

Image

Layering it on

For an application like the Naan & Pop site, your team will build logical components to match the problem. But how will you implement those components?

Layers, in this type of architecture, are created with packages or namespaces, just like domain components. However, to maintain the separation of concerns, the layers’ package structures typically reflect their place within the partitioning:

com.naanpop.orderapp.presentation
com.naanpop.orderapp.workflow
com.naanpop.orderapp.model
com.naanpop.orderapp.persistence
Note

The fully qualified names of these layers will appear as packages in Java, namespaces in .NET, or whatever namespacing mechanism your language of choice uses.

Like the logical components, the architectural layers use the component implementation of the underlying platform, which often maps to the underlying filesystem:

Image

Translating layers into code

Once your team has built the component packages (or namespaces), you’ll need to assist the developers in implementing the architecture. Here’s an example in Python-like pseudocode to illustrate how the layers translate to code.

  • Images The user interface layer , or presentation layer , is the topmost layer. It’s responsible for interacting with the user, serving the same purpose as the view part of MVC.

    Image

  • Images The workflow layer (sometimes called the business rules layer ) is responsible for processing each request from the UI layer and returning a response.

    Image

  • Images The persistence layer (or data access layer ) is responsible for accessing the data from the database and returning it to the workflow layer.

    Image

there are no Dumb Questions

Q: You said in Chapter 5 that every architectural style has a category and a philosophy. Where does the layered architecture fit in?

A: We’re glad you’re thinking about that. As we said in Chapter 5 , understanding the categories reveals a lot about what characteristics a particular architectural style will support.

The layered architecture is a technically partitioned architectural style, typically deployed as a monolith. (We say typically because we’ll discuss some variations on this model soon.)

Image

This is an important point—the domain behavior lives across the layers in this architecture.

The domain , as you’ll recall, represents logical components based on the problem you’re trying to solve. However, the layers in this architecture represent technical capabilities—user interface, business logic, and so on.

The domain maps onto the layered architecture, sometimes spreading between layers.

there are no Dumb Questions

Q: Why these particular layers—presentation, workflow, and persistence?

A: These are common layers, but they are by no means required. Most applications have at least some of this separation: for instance, the UI is often distinct from the core logic of the system, which in turn is separate from the database development.

Q: Was the layered architecture inspired by the Model-View-Controller design pattern?

A: The opposite is likely true. Layered architectures, which have existed as long as people have been building software from different parts, may well have inspired the design pattern. Design patterns are often harvested from observations of common occurrences, and the layered architecture has been around for quite some time in many forms.

Domains, components, and layers

In a simple restaurant ordering system like Naan & Pop’s, we might come up with the following components based on the problem domain:

Image

But there’s a problem. These components are based on the logical behavior of the domain, but the layered architecture splits things by capabilities . So, we need to separate the logical components (which include workflows and entities) into components that match what we need for the layered architecture:

Image

Once we’ve split the logical components into workflow and entities, we can overlay the components over the layers in this architecture:

Image

Sharpen your pencil

Image

Naan & Pop’s lead architects have designed a layered architecture. Today, though, they’re off at a daylong breadmaking seminar to learn more about their problem domain, leaving you to sort out which components go where. Can you decide in which layer (or layers) each component should reside? Draw the components below on the layer(s) to which they should map.

Image

Image

Image Solution in “Sharpen your pencil Solution”

Image

there are no Dumb Questions

Q: Why go to the trouble of identifying logical components if we have to break them apart to fit them into this architecture?

A: The logical components represent the problem you’re trying to solve. Mapping that to any architecture means applying real-world constraints (and trade-offs). We’ll show you a more direct domain-to-architecture mapping in the next chapter, but it has trade-offs, too.

Q: Why is the layered architecture so popular?

A: This architecture shows up a lot. First, it’s simple, without many moving parts. Second, as you’ve seen, it maps closely to the MVC design pattern, making it easy to understand. Third, it’s so common that teams can build simple projects quickly in this style. Fourth, many companies separate their employees by skill set, which facilitates an architecture with similar partitions.

Drivers for layered architecture

We’ve put together a list of the things the layered architecture is really good at—that is, the things that might drive us toward picking this particular architectural style.

Image

Specialization

Using a layered architecture allows organizations to split teams into specialists, sharing their capabilities between different projects.

Note

The ability to specialize makes this architecture popular in organizations that need to share special skills across multiple projects.

Image

Matches physical separation

The layered architecture typically separates the logical components to match the physical separation. For example, it’s common for teams to implement different layers in different technology stacks (such as JavaScript, Java, and MySQL).

Note

Often, the real world prevents architects from designing what they want, instead forcing them to design with what they have.

Image

Ease of (technical) reuse

Splitting the architecture by technical capabilities allows better opportunities to reuse code. For example, if all persistence code resides in a single layer, it’s easier for developers to find, update, and reuse it.

Note

The ability to reuse components within a layer is one of the key advantages of this architecture for many organizations.

Image

Conceptual twin of MVC

Simplicity and concerns about feasibility are driving forces in many architectures. Developers find it easier to understand and work within an architecture that matches familiar design patterns, such as MVC.

Note

Feasibility and simplicity for the win!

Layers, meet the real world: Physical architectures

The layered monolith describes a logical architecture, but architects may implement that logical architecture in a variety of physical architectures.

Image

Image

Physical architecture trade-offs

Which physical architecture should you choose? Well, they all have trade-offs, like everything in software architecture.

Image

Image

Exercise

Image

Generic trade-offs are one thing, but software architecture is always based on a real system. The architects at Naan & Pop need some help evaluating the trade-offs for each physical architecture as they decide which one to use. Can you help them figure out which specific trade-offs the Naan & Pop application will face for each physical architecture?

Image

Images Solution in “Exercise Solution”

Cubicle conversation

Image

Alex: Is Naan & Pop generic enough to only use the standard layers? When do teams add layers?

Sam: Why add layers to the architecture?

Mara: Each layer in a layered architecture has a specific responsibility within the system, so when they’re needed, we add layers.

Sam: What kinds of layers?

Alex: It’s common to add a services layer, which provides access for business-to-business integration, or integration layers for other internal systems. Each request goes through each layer, so layers need to be things that happen to every request.

Image

Mara: That’s right—architects can add whatever layers we need to support some new behavior. For example, the site needs integration with third-party delivery services, so maybe we should add an integration layer. Here, let me draw what I have in mind for our layered architecture on the whiteboard...

Image

Alex: Adding an integration layer for our delivery hooks would make things easier, wouldn’t it? It looks like all the code pertaining to that integration lives in the same place, which would make it easy to find and update.

Mara: Yes, and that’s true for the user interface layer, too. In fact, one of the next requirements we have to implement is an additional UI to support mobile.

Sam: So, if we add a separate mobile UI, we’d only have to change one layer?

Mara: That’s one of the best things about layered architecture!

Image

One final caveat about domain changes

One of the primary advantages of a layered architecture is that it lets us group similar technical things together. For example, in the Naan & Pop application, separating the UI into its own set of components allows the team to add new UI types without affecting the other layers.

Let’s pause for a second and think about this—what about changes to the problem domain? If Naan & Pop wanted to add something other than sandwiches to the menu, like pizza, would every layer have to change?

The power to change things in isolation is the layered architecture’s superpower, but it’s not a silver bullet. This architectural style’s big trade-off is that the problem domain is smeared across the layers in the architecture. For example, the Place Order logical component in the Naan & Pop architecture requires a UI (presentation), code to implement the workflow (workflow), and a data schema (persistence).

That means that technical capabilities are easy to change and enhance, but domain changes can create side effects that ripple through the layers.

Note

We alluded to this earlier in the chapter.

Layered architectures facilitate technical changes but make domain changes more difficult.

So, what to do? Well, there’s a reason why we started this book by showing you how to identify the architectural characteristics your application needs to support. If continual, significant domain changes are expected or suddenly become a higher priority, there are other architectural styles to consider.

Note

Take a deep breath. The next chapter will introduce you to an architectural style that is better suited to accommodating domain changes. Oh, the suspense!

All that said, let’s quickly summarize the good and bad of the layered architecture.

there are no Dumb Questions

Q: That’s a rather large caveat. Why would I even consider the layered architectural style?

A: Remember the First Law of Software Architecture—everything’s a trade-off. Sure, other architectural styles might allow for easier changes to the domain, but they have their own caveats. Align the strengths and weaknesses of every architectural style with your requirements, and then choose. There’s no one right choice, just the choice that works best for your particular set of circumstances.

Layered architecture superpowers

Layered architectures have been demonstrating their powers for many, many years—this is one of the oldest recognizable architectural styles.

Image

Image

Feasibility

If time and budget are overwhelmingly important, the simplicity of this architecture is quite appealing.

Note

If your whole company runs on investment dollars, feasibility is especially important.

Image

Technical partitioning

Architects design components around technical capabilities, making it easier for them to reuse common capabilities. For example, if several teams need the same data functionality, they could implement it once in a persistence layer and then share it across teams.

Data-intensive

Systems that do a lot of data-level processing may benefit from a layered architecture because it isolates data processing in a single database that’s optimized for the task.

Note

In general, the less a system needs to access data over the network, the more efficient it can be.

Performance

Well-designed layered monoliths can demonstrate high performance—making no network calls and processing data in a single place (the monolithic database) means there’s no need for network calls that could decrease performance.

Quick to build

Simplicity plus a single work/deployment unit means that teams can build small systems quite rapidly.

Lean and mean

Keeping these systems small helps avoid some of the kryptonite on the next page.

Image

Layered architecture kryptonite

This architecture is pervasive and popular, but it can be overused and even abused. While feasibility may be a superpower, many teams default to this architecture because of its simplicity, long history, and widespread use, without considering if it’s really the most suitable option.

Image

Deployability

As monolithic systems get bigger, deployments tend to become more complex—especially when developers keep adding behavior.

Big ball of mud

Because everything is connected to everything else, this architecture can become a highly coupled mess without careful governance.

Scalability

Probably the biggest problem with monoliths is that when you only have one bucket and you keep adding things to it, it will eventually fill up. The same is true for monoliths generally, which eventually become constrained by some resource (memory bandwidth, and so on).

Elasticity

A single process has a harder time dealing with sudden bursts of users.

Image

Testability

High coupling and a large codebase make testing harder and harder over time.

Image

Layered architecture star ratings

The Naan & Pop architecture team decides to use a rating chart they found in the book Fundamentals of Software Architecture (O’Reilly), written by two of your authors, that describes the layered architecture in a convenient way. One star means that the architectural characteristic is not well supported; five stars means the architectural characteristic is very well supported.

Note

Just like movie reviews.

Image

Exercise

Image

Which of the following systems might be well suited for the layered monolithic architectural style, and why? Hint: Take into account its superpowers, its kryptonite, and the nature of the system.

Image

Image Solution in “Exercise Solution”

Wrapping it up

Congratulations! The Naan & Pop team looked at several architectural styles, but after considering the business’s priorities, you chose a layered architecture. This paid off handsomely, allowing the business to grow without any problems.

Bullet Points

  • A layered architecture is monolithic : the entire system (code and database) is deployed as a single unit.

  • The layers are separated by technical capabilities. Typical layers in this architecture include presentation (for the user interface), business rules (for the workflow and logic of the application), and persistence (facilities to support databases for systems that need persistent data).

  • The layered architecture supports feasibility well; it is easy to understand and it lets you build simple systems fast.

  • The layered architecture supports excellent separation of technical concerns, making it easy to add new capabilities like user interfaces or databases.

  • The layered architecture mimics some of the same concerns as the Model-View-Controller design pattern, but translated into physical layers and subject to real-world constraints.

  • User requests flow through the user interface and through each layer before a response is returned to the user.

  • Each request in this architecture goes through each layer.

  • A layered architecture’s capabilities degrade over time if teams continue to add functionality due to eventual resource limits (for example, they run out of capacity).

  • The layered architecture provides excellent support for specialization (user interface designers, coders, database experts, and so on).

  • Logical components represent the problem domain, yet layers focus on technical capabilities, requiring translation between the domain and architecture layers.

  • A layered architecture may manifest in several physical architectures, including two-tier (also known as client/server ), three-tier (web), and embedded/mobile .

  • Changing and adding to the technical capabilities represented in layers is easy; the layered architecture facilitates this.

  • Changing the problem domain requires coordination across the layers of the architecture, making domain changes more difficult.

Layered Architecture Crossword

Image

Ready to add learning on top of learning by solving the layers of this crossword?

Image

Across

3. Layered architectures use familiar design _____

5. Kind of layered architecture often found in smartphone apps

6. Type of architecture covered in this chapter

8. _____ can be confined to one layer

9. Namespaces and packages correspond to the directory _____

11. Too much coupling can lead to a big ball of _____

14. Layer that maps object models to relational models for databases

17. Depending on the network for data access makes an architecture _____ reliable

19. Kind of database often used for persistence

21. Layered architectures might have two or more _____

Down

1. The integration layer lets the system _____ with third parties

2. Layered architectures facilitate _____

4. The _____ domain spreads across all of the layers

7. Logical and _____ components are usually separated in the same way

10. Logical _____ reside in layers

12. Domain-driven _____

13. Layer that applies business rules

15. The user _____ is part of the presentation layer

16. The MVC pattern and layered architecture both _____ responsibilities

18. A user’s request and its response _____ through the layers

20. Model-_____-Controller design pattern

Image Solution in “Layered Architecture Crossword Solution”

From “Sharpen your pencil”

Sharpen your pencil Solution

Image

Naan & Pop’s lead architects have designed a layered architecture. Today, though, they’re off at a daylong breadmaking seminar to learn more about their problem domain, leaving you to sort out which components go where. Can you decide in which layer (or layers) each component should reside? Draw the components below on the layer(s) to which they should map.

Image

From “Exercise”

Exercise Solution

Image

Generic trade-offs are one thing, but software architecture is always based on a real system. The architects at Naan & Pop need some help evaluating the trade-offs for each physical architecture as they decide which one to use. Can you help them figure out which specific trade-offs the Naan & Pop application will face for each physical architecture?

Image

From “Exercise”

Exercise Solution

Image

Which of the following systems might be well suited for the layered monolithic architectural style, and why? Hint: Take into account its superpowers, its kryptonite, and the nature of the system.

Image

Layered Architecture Crossword Solution

Image

From “Layered Architecture Crossword”

Image