Get Your Hands Dirty on Clean Architecture - Tom Hombergs - E-Book

Get Your Hands Dirty on Clean Architecture E-Book

Tom Hombergs

0,0
29,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Building for maintainability is key to keep development costs low (and developers happy). The second edition of "Get Your Hands Dirty on Clean Architecture" is here to equip you with the essential skills and knowledge to build maintainable software.
Building upon the success of the first edition, this comprehensive guide explores the drawbacks of conventional layered architecture and highlights the advantages of domain-centric styles such as Robert C. Martin's Clean Architecture and Alistair Cockburn's Hexagonal Architecture. Then, the book dives into hands-on chapters that show you how to manifest a Hexagonal Architecture in actual code. You'll learn in detail about different mapping strategies between the layers of a Hexagonal Architecture and see how to assemble the architecture elements into an application. The later chapters demonstrate how to enforce architecture boundaries, what shortcuts produce what types of technical debt, and how, sometimes, it is a good idea to willingly take on those debts.
By the end of this second edition, you'll be armed with a deep understanding of the Hexagonal Architecture style and be ready to create maintainable web applications that save money and time. Whether you're a seasoned developer or a newcomer to the field, "Get Your Hands Dirty on Clean Architecture" will empower you to take your software architecture skills to new heights and build applications that stand the test of time.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 222

Veröffentlichungsjahr: 2023

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Get Your Hands Dirty on Clean Architecture

Build ‘clean’ applications with code examples in Java

Tom Hombergs

BIRMINGHAM—MUMBAI

Get Your Hands Dirty on Clean Architecture

Copyright © 2023 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

Group Product Manager: Gebin George

Publishing Product Manager: Kunal Sawant

Senior Editor: Ruvika Rao

Technical Editor: Jubit Pincy

Copy Editor: Safis Editing

Project Coordinator: Manisha Singh

Proofreader: Safis Editing

Indexer: Tejal Daruwale Soni

Production Designer: Joshua Misquitta

Marketing Coordinator: Sonia Chauhan

First published: September 2019

Second edition: July 2023

Production reference: 1300623

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-80512-837-3

www.packtpub.com

To my wife, Rike, and my kids, Nora and Niklas, for regularly reminding me that there is a life outside of software development.

– Tom Hombergs

Foreword

It’s a developer’s paradise: it's easy to test the domain logic, it's easy to mock out infrastructure and technology, there's a crystal-clear separation of domain code and technical code, and even migrating from one technology to another seems easy. No more endless discussion about in which part of your code you should implement this tricky new feature in that the business people need by tomorrow. It’s called Clean Architecture,” and Tom will guide you on your journey toward this.

For a few years, the foundation of clean architecture has been documented under various names (Hexagonal Architecture, ports and adapters, onion architecture, and clean architecture). The basic idea looks simple: two concentric circles separating domain stuff and technical stuff within the software. Dependencies flow inward, from technology to the domain. Domain classes are not allowed any dependencies upon technical classes.

Too bad that most of the original sources missed out on explaining how packages and code should be organized. Tom’s book perfectly fills this gap. He uses an illustrative example to guide you toward a highly maintainable and clear architectural structure.

Do yourself and your development colleagues a favor and give the clean architecture approach a chance. I promise you won’t regret it!

Gernot Starke

Cologne, June 2023

Pragmatic software architect since the 1990s, founder of arc42, co-founder of iSAQB, and nerd

Contributors

About the author

Tom Hombergs is a software engineer, author, and simplicity nerd. Complexity is his kryptonite, so he works hard on breaking complex things down into simple pieces that he can understand. If he can understand it, everyone else can, too. He simplifies code as well as text, creating articles, books, and developer documentation that are a joy to read. Tom currently works at Atlassian in Sydney, Australia, where he is responsible for the Developer Experience (DX) of the tech stacks used by other Atlassian developers.

About the reviewers

Alexandros Trifyllis is a freelance software engineer with 15 years of experience. He has been part of large enterprise projects for the public, private, and European sectors.

His areas of interest include backend development (Spring Boot), frontend development (Angular), and various architecture practices (hexagonal/DDD). He also likes to get involved with DevOps tasks (AWS, Terraform, and Kubernetes). Finally, in the past few years, he has taken an interest in DX and Developer Productivity Engineering (DPE) and generally in thinking about how to make the job of developers easier and more pleasant.

Artem Gorbounov is a Java full-stack developer with a passion for clean architecture and 5 years of industry experience. Currently working at OneUp, he specializes in building robust and scalable web applications. Artem holds an Amazon certification, demonstrating his expertise in cloud computing technologies. He believes that a real full stack programmer should have a comprehensive understanding of the entire technological stack, from the database to the infrastructure, with a clear understanding of application architecture.

Dr. Gernot Starke is a coach and consultant for software architecture, an INNOQ fellow, the co-founder of arc42 and iSAQB, the founder of aim42, the former technical director of the Sun Microsystems Object-Reality-Center, and a nerd who enjoys bulletproof coffee.

Jonas Havers is a freelance full stack software engineer with more than 15 years of professional experience working for international e-commerce companies. As a solution and application architect, he helps clients design and build custom large-scale business software systems that help them respond quickly to change and become more successful in their market. He is adept at using a variety of tools, methodologies, and programming languages, including Java, Kotlin, and JavaScript. Jonas regularly explains, discusses, and implements various software designs and software architectures and loves to share all his knowledge and experience with his project team members as well as with his students as a sought-after university guest lecturer.

Jörg Gellien helps teams in an innovative company to design and develop modern, highly scalable applications to achieve the right business needs. He is an expert on software architecture and Java/Spring development. The ideas of end-to-end responsibility for a product and the use of cloud-based services are strong drivers for his work.

Jo Vanthournout has been a Java developer and architect for nearly 20 years. He was fortunate to start his career as a developer on one of the first extreme programming projects in Belgium. Ever since, he had tried to live and breathe the values of agile development. Jo has an avid interest in DDD and uses its principles and techniques on a daily basis. He will never be the best developer on the team, but having a pragmatic helicopter view of the problem domain at hand, asking nasty questions, and holding members accountable to the team values are tasks you can entrust him with. He has a wonderful wife and two daughters. When not coding, he is out in the woods running, visiting a battleground from the Second World War, or playing Minecraft with his kids.

K. Siva Prasad Reddy is a software architect with more than 18 years of experience in building scalable software systems, primarily using the Java platform.

He is an avid follower of agile practices and takes a pragmatic approach to software design and architecture. He shares his learning and thoughts at https://sivalabs.in.

Lorenzo Bettini (https://www.lorenzobettini.it) is an associate professor in computer science at DISIA, Università di Firenze, Italy. His research covers the design, theory, and implementation of programming languages, with IDE support.

He is the author of more than 90 research papers, published in international conferences and international journals, of two editions of the book Implementing Domain-Specific Languages with Xtext and Xtend (Packt Publishing), and the book Test-Driven Development, Build Automation, Continuous Integration (with Java, Eclipse and friends) (Leanpub).

Maria Luisa Della Vedova is a passionate software developer dedicated to creating meaningful and user-centric solutions, continuously learning and collaborating to have a positive impact on people’s lives.

Matt Penning has provided companies with technical direction and software development for over three decades. He has a proven track record of creating well-defined and innovative architectures that solve real-world problems and is currently working as a senior technical leader at Cisco Systems, Inc., where he is immersed in Java microservice development, software quality, and developer productivity.

Mike Davidson is a lead developer and application architect. He works with New Zealand-based, Canadian, and US start-ups and financial institutions to help them build maintainable, cleanly structured software.

Octavian Nita has dabbled professionally and for fun in Java for over 18 years, moving from language implementation and software automation to desktop and web-based applications. He still enjoys doing that very much. Brussels-based, these days, he helps European public administration bodies implement so-called “enterprise applications” using domain-centric architecture styles.

Sven Woltmann has been a Java developer since the early days. He works as an independent developer, coach, and course instructor, specializing in highly scalable Java enterprise applications, algorithm optimization, clean code, and clean architecture. He also shares his knowledge through videos, a newsletter, and his blog, HappyCoders.eu.

Thomas Buss is an IT consultant at codecentric in Germany. He helps teams reduce the complexity of software products and thus speed up the development process. Coming from a Java background, he enjoys looking into other paradigms and languages as well. He’s also interested in domain-driven modeling, serverless technologies, and ways to reduce the carbon footprint of systems. Also, he likes TV shows that start with “Star.”

Vivek Ravikumar currently works as a member of the technical staff at PayPal India and has almost a decade of experience in developing enterprise web applications. He has held multiple seminars and lectures across educational institutions and universities in India advocating the importance and best practices involved in the software development life cycle, mentoring students, and fostering industrial knowledge.

Recently, he has been recognized as a legend of Jakarta EE, MicroProfile, and the Payara platform for securing the top spot in the first-ever Payara global hackathon in building an enterprise web application.

Wim Deblauwe is a freelance Java developer with over 20 years of Java experience. He is the author of Taming Thymeleaf and Practical Guide to Building an API Back End with Spring Boot. He also started and contributed to various open source projects such as error-handling-spring-boot-starter and testcontainers-cypress.

Table of Contents

Preface

1

Maintainability

What does maintainability even mean?

Maintainability enables functionality

Maintainability generates developer joy

Maintainability supports decision-making

Maintaining maintainability

2

What’s Wrong with Layers?

They promote database-driven design

They’re prone to shortcuts

They grow hard to test

They hide the use cases

They make parallel work difficult

How does this help me build maintainable software?

3

Inverting Dependencies

The Single Responsibility Principle

A tale about side effects

The Dependency Inversion Principle

Clean Architecture

Hexagonal Architecture

How does this help me build maintainable software?

4

Organizing Code

Organizing By Layer

Organizing by feature

An architecturally expressive package structure

The role of dependency injection

How does this help me build maintainable software?

5

Implementing a Use Case

Implementing the domain model

A use case in a nutshell

Validating input

The power of constructors

Different input models for different use cases

Validating business rules

Rich versus anemic domain model

Different output models for different use cases

What about read-only use cases?

How does this help me build maintainable software?

6

Implementing a Web Adapter

Dependency Inversion

Responsibilities of a web adapter

Slicing controllers

How does this help me build maintainable software?

7

Implementing a Persistence Adapter

Dependency inversion

Responsibilities of a persistence adapter

Slicing port interfaces

Slicing persistence adapters

An example with Spring Data JPA

What about database transactions?

How does this help me build maintainable software?

8

Testing Architecture Elements

The test pyramid

Testing a domain entity with unit tests

Testing a use case with unit tests

Testing a web adapter with integration tests

Testing a persistence adapter with integration tests

Testing main paths with system tests

How much testing is enough?

How does this help me build maintainable software?

9

Mapping between Boundaries

The “No Mapping” strategy

The “Two-Way” mapping strategy

The “Full” mapping strategy

The “One-Way” mapping strategy

When to use which mapping strategy?

How does this help me build maintainable software?

10

Assembling the Application

Why even care about assembly?

Assembling via plain code

Assembling via Spring’s classpath scanning

Assembling via Spring’s Java Config

How does this help me build maintainable software?

11

Taking Shortcuts Consciously

Why shortcuts are like broken windows

The responsibility of starting clean

Sharing models between use cases

Using domain entities as the input or output model

Skipping incoming ports

Skipping services

How does this help me build maintainable software?

12

Enforcing Architecture Boundaries

Boundaries and dependencies

Visibility modifiers

Post-compile fitness function

Build artifacts

How does this help me build maintainable software?

13

Managing Multiple Bounded Contexts

One hexagon per bounded context?

Decoupled bounded contexts

Appropriately coupled bounded contexts

How does this help me build maintainable software?

14

A Component-Based Approach to Software Architecture

Modularity through components

Case study – building a “Check Engine” component

Enforcing component boundaries

How does this help me build maintainable software?

15

Deciding on an Architecture Style

Start simple

Evolve the domain

Trust your experience

It depends

Index

Other Books You May Enjoy

Preface

If you have picked up this book, you care about the architecture of the software you’re building. You want your software to not only fulfill the customer’s explicit requirements but also the hidden requirement of maintainability, and your own requirements concerning structure and aesthetics.

It’s hard to fulfill these requirements because software projects (or projects in general, for that matter) usually don’t go as planned. Managers draw deadlines all around the project team1, external partners build their APIs differently from what they had promised, and the software products we depend on don’t work as expected.

1 The word “deadline” presumably originates from the 19th century and described a line drawn around a prison or a camp of prisoners. A prisoner that crossed that line was shot. Think about this definition the next time someone “draws a deadline” around you... it will certainly open up new perspectives. See https://www.merriam-webster.com/words-at-play/your-deadline-wont-kill-you.

And then there is our own software architecture. It was so nice in the beginning. Everything was clear and beautiful. Then the deadlines pressed us into taking shortcuts. Now, the shortcuts are all that’s left of the architecture, and it takes longer and longer to deliver new features.

Our shortcut-driven architecture makes it hard to react to an API that had to be changed because an external partner screwed up. It seems easier to just send our project manager into battle with that partner to tell them to deliver the API we had agreed upon.

Now, we have given up all control over the situation. In all likelihood, one of the following things will happen:

The project manager is not strong enough to win the battle against the external partnerThe external partner finds a loophole in the API specs, proving them rightThe external partner needs another <enter number here> months to fix the API

All of this leads to the same result – we have to change our code quickly because the deadline is looming.

We add another shortcut.

Instead of letting external factors govern the state of our software architecture, this book takes the stance of taking control ourselves. We gain this control by creating an architecture that makes the software soft, as in “flexible,” “extensible,” and “adaptable.” Such an architecture will make it easy to react to external factors and take a lot of pressure off our backs.

The goal of this book

I wrote this book because I was disappointed with the practicality of the resources available on domain-centric architecture styles, such as Robert C. Martin’s Clean Architecture and Alistair Cockburn’s Hexagonal Architecture.

Many books and online resources explain valuable concepts but not how we can actually implement them.

That’s probably because there is more than one way to implement any architecture style.

With this book, I am trying to fill this void by providing a hands-on-code discussion about creating a web application in the Hexagonal Architecture or “Ports and Adapters” style. In order to live up to that goal, the code examples and concepts discussed in this book provide my interpretation of how to implement a Hexagonal Architecture. There are certainly other interpretations out there, and I do not claim that mine is authoritative.

I certainly hope, however, that you will get some inspiration from the concepts in this book so that you can create your own interpretation of Hexagonal/Clean Architecture.

Who this book is for

This book is aimed at software developers of all experience levels involved in creating web applications. As a junior developer, you’ll learn about how to design software components and complete applications in a clean and maintainable manner. You will also learn some arguments for when to apply a certain technique. You should, however, have participated in building a web application in the past to get the most out of this book. If you’re an experienced developer, you’ll enjoy comparing the concepts from the book with your own way of doing things and, hopefully, incorporating bits and pieces into your own software development style. The code examples in this book are in Java and Kotlin, but all discussions are equally applicable to other object-oriented programming languages. If you’re not a Java programmer but can read object-oriented code in other languages, you’ll be fine. In the few places where we need some Java or framework specifics, I will explain them.

The example application

To have a recurrent theme throughout the book, most of the code examples show code from an example web application for transferring money online. We’ll call it “BuckPal.”2

2 BuckPal: a quick online search has revealed that a company named PayPal has stolen my idea and even copied part of the name. Joking aside: try to find a name similar to “PayPal” that is not the name of an existing company. It’s hilarious!

The BuckPal application allows a user to register an account, transfer money between accounts, and view the activities (deposits and withdrawals) on the account.

I’m not a finance specialist by any means, so please don’t judge the example code based on legal or functional correctness. Rather, judge it on structure and maintainability.

The curse of example applications for software engineering books and online resources is that they’re too simple to highlight the real-world problems we struggle with every day. On the other hand, an example application must stay simple enough to effectively convey the discussed concepts.

I hope to have found a balance between “too simple” and “too complex” as we discuss the use cases of the BuckPal application throughout this book.

The code of the example application can be found on GitHub.3

3 The BuckPal GitHub repository: https://github.com/thombergs/buckpal.

Download the color images

We also provide a PDF file that has color images of the screenshots and diagrams used in this book. Check the notes at the end of the book.4

4 PDF with color images used in this book: https://packt.link/eBKMn.

Get in touch

If you have anything to say about this book, I’d love to hear it! Get in touch with me directly via email to [email protected] or on Twitter via @TomHombergs.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share your thoughts

Once you’ve read Get Your Hands Dirty on Clean Architecture–Second Edition, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere?

Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application.

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/9781805128373

2. Submit your proof of purchase

3. That’s it! We’ll send your free PDF and other benefits to your email directly

1

Maintainability

This book is about software architecture. One of the definitions of architecture is the structure of a system or process. In our case, it’s the structure of a software system.

Architecture is designing this structure with a purpose. We’re consciously designing our software system to fulfill certain requirements. There are functional requirements that the software has to fulfill to create value for its users. Without functionality, software is worthless, because it produces no value.

There are alsoquality requirements (also called non-functional requirements) that the software should fulfill to be considered high quality by its users, developers, and stakeholders. One such quality requirementis maintainability.

What would you say if I told you that maintainability as a quality attribute, in a way, is more important than functionality and that we should design our software for maintainability over everything else? Once we have established maintainability as an important quality, we will use the rest of this book to explore how we can improve the maintainability of our software by applying the concepts of Clean and Hexagonal Architecture.

What does maintainability even mean?

Before you write me off as a lunatic and start looking for options to return this book, let me explain what I mean by maintainability.

Maintainability is only one of the many quality requirements that potentially make up a software architecture. I asked ChatGPT for a list of quality requirements, and this is the result:

ScalabilityFlexibilityMaintainabilitySecurityReliabilityModularityPerformanceInteroperabilityTestabilityCost-effectiveness

The list doesn’t end here.1

1 For some inspiration about software quality (which has been created by humans, and not a language model), have a look at https://quality.arc42.org/.

As software architects, we design our software to fulfill the quality requirements that are most important for the software. For a high-throughput trading application, we might focus on scalability and reliability. For an application dealing with personally identifiable information in Germany, we might want to focus on security.

I think it’s wrong to lump maintainability in with the rest of the quality requirements because maintainability is special. If software is maintainable, that means it’s easy to change. If it’s easy to change, it’s flexible and probably modular. It’s probably cost-effective, too, because easy changes mean cheap changes. If it’s maintainable, we can probably evolve it to be scalable, secure, reliable, and performant, should the need arise. We can change the software to be interoperable with other systems because it’s easy to change. Last but not least, maintainability implies testability because maintainable software is most likely designed from smaller and simpler components that make testing easy.

You can see what I did here. I asked AI for a list of quality requirements and then tied them all back to maintainability. I could probably tie many more quality requirements back to maintainability with similarly plausible arguments. It’s a bit simplistic, of course, but the core of it is true: if software is maintainable, it’s easier to evolve in any direction, functionally and non-functionally. And we all know that change is common during the life of a software system.

Maintainability enables functionality

Now back to my claim that maintainability is more important than functionality from the beginning of this chapter.

If you ask a product person what’s most important in a software project, they’ll tell you that the value the software provides to its users is the most important thing. Software that doesn’t provide value to its users means that users don’t pay for it. And without paying users, we don’t have a working business model, which is the main measure of success in the business world.

So, our software needs to provide value. But it shouldn’t provide value at the cost of maintainability.2 Think about how much more efficient and joyful it is to add functionality to a software system that is easily changeable as compared to a software system where you have to fight your way through one line of code at a time! I’m pretty sure that you’ve worked on one of those software projects where there’s so much cruft and ritual that it takes days or weeks to build a feature that you think should take no more than a couple of hours to complete.

2 In the context of this book, I use the term "maintainability" synonymously with "changeability of a code base". Also see https://quality.arc42.org/qualities/maintainability for some definitions of maintainability (all of which have to do with changing the software).

In this way, maintainability is a key supporter of functionality. Bad maintainability means that changes in functionality become more and more expensive over time, as shown in Figure 1.1:

Figure 1.1 – A maintainable software system has a smaller lifetime cost than a not-so-maintainable software system

In a not-so-maintainable software system, changes in functionality will soon become so expensive that change is a pain. Product people will complain to the engineers about the cost of changes. The engineers will defend themselves by saying that shipping new features has always had a higher priority than increasing maintainability. The probability of conflict increases with the cost of change.

Maintainability is a pacifier. It’s inversely proportional to the cost of change and thus to the probability of conflict. Did you ever think about adding maintainability to a software system to avoid conflict? I think that’s a good investment in itself.

But what about those big software systems that are successful in spite of bad maintainability? It’s true that there are commercially successful software systems out there that are barely maintainable. I’ve worked on systems where adding a single field to a form is a project that takes weeks of developer time, and the client happily paid a premium for my time.

Those systems usually fall into one (or both) of two categories:

They are at the end of their life where changes to the system are few and