This blog post is a follow-up to the discussions I've had with people after my recent Modular Monoliths talks. I've been enthusiastically told that the "ports & adapters" (hexagonal) architectural style is "vastly", "radically" and "hugely" different to a traditional layered architecture. I remain unconvinced, hence this blog post, which has a Java spin, but I'm also interested in how the concepts map to other programming languages. I'm also interested in exploring how we can better structure our code to prevent applications becoming big balls of mud. Layers are not the only option.
Imagine you're building a simple web application where users interact with a web page and information is stored in a database. The UML class diagrams that follow illustrate some of the typical ways that the source code elements might be organised.
Let's first list out the types in the leftmost diagram:
I'll talk about the use of interfaces later, but let's assume we're going to use interfaces for the purposes of dependency injection, substitution, testing, etc. Now let's look at the four UML class diagrams, from left to right.
On the face of it, these do all look like different ways to organise code and, therefore, different architectural styles. This starts to unravel very quickly once you start looking at code examples though. Take a look at the following example implementations of the ports & adapters style.
Spot anything? Yes, the interface (port) and implementation class (adapter) are both public. Most of the code examples I've found on the web have liberal usage of the public access modifier. And the same is true for examples of layered architectures. Marking all types as public means you're not taking advantage of the facilities that Java provides with regards to encapsulation. In some cases there's nothing preventing somebody writing some code to instantiate the concrete repository implementation, violating the architecture style. Coaching, discipline, code reviews and automated architecture violation checks in the build pipeline would catch this, assuming you have them. My experience suggests otherwise, especially when budgets and deadlines start to become tight. If left unchecked, this is what can turn a codebase into a big ball of mud.
Looking at this another way, when you make all types in your application public, the packages are simply an organisation mechanism (a grouping, like folders) rather than being used for encapsulation. Since public types can be used from anywhere in a codebase, you can effectively ignore the packages. The net result is that if you ignore the packages (because they don't provide any means of encapsulation and hiding), a ports & adapters architecture is really just a layered architecture with some different naming. In fact, if all types are public, all four options presented before are exactly the same.
Conceptually ports & adapters is different from a traditional layered architecture, but syntactically it's really the same, especially if all types are marked as public. It's a well implemented n-layer architecture, where n is the number of layers through a slice of the application (e.g. 3; web-domain-database).
The way Java types are placed into packages can actually make a huge difference to how accessible (or inaccessible) those types can be when Java's access modifiers are applied appropriately. Ignoring the controllers ... if I bring the packages back and mark (by fading) those types where the access modifier can be made more restrictive, the picture becomes pretty interesting.
The use of Java's access modifiers does provide a degree of differentiation between a layered architecture and a ports & adapters architecture, but I still wouldn't say they are "vastly" different. Bundling the types into a smaller number of packages (options 3 & 4) allows for something a little more radical. Since there are fewer inter-package dependencies, you can start to restrict the access modifiers. Java does allow interfaces to be marked as package protected (the default modifier) although if you do this you'll notice that the methods must still be marked as public. Having public methods on a type that's inaccessible outside of the package is a little odd, but it's not the end of the world.
With option 3, "vertical slicing", you can take this to the extreme and make all types package protected. The caveat here is that no other code (e.g. web controllers) outside of the package will be able to easily reuse functionality provided by the CustomerService. This is not good or bad, it's just a trade-off of the approach. I don't often see interfaces being marked as package protected, but you can use this to your advantage with frameworks like Spring. Here's an example from Oliver Gierke that does just this (the implementation is created by the framework). Actually, Oliver's blog post titled Whoops! Where did my architecture go, which is about reducing the number of public types in a codebase, is a recommended read.
I'm not keen on how the presentation tier (CustomerController) is coupled in option 3, so I tend to use option 4. Re-introducing an inter-package dependency forces you to make the CustomerComponent interface public again, but I like this because it provides a single API into the functionality contained within the package. This means I can easily reuse that functionality across other web controllers, other UIs, APIs, etc. Provided you're not cheating and using reflection, the smaller number of public types results in a smaller number of possible dependencies. Options 3 & 4 don't allow callers to go behind the service, directly to the DAO. Again, I like this because it provides an additional degree of encapsulation and modularity. The architecture rules are also simpler and easier to enforce, because the compiler can do some of this work for you. This echoes the very same design principles and approach to modularity that you'll find in a modern microservices architecture: a remotable service interface with a private implementation. This is no coincidence. Caveats apply (e.g. don't have all of your components share a single database schema) but a well-structured modular monolith will be easier to transform into a microservices architecture.
In the spirit of YAGNI, you might realise that some of those package protected DAO interfaces in options 3 and 4 aren't really necessary because there is only a single implementation. This post isn't about testing, so I'm just going to point you to Unit and integration are ambiguous names for tests. As I mention in my "Modular Monoliths" talk though, I think there's an interesting relationship between the architecture, the organisation of the code and the tests. I would like to see a much more architecturally-aligned approach to testing.
I've had the same discussion about layers vs ports & adapters with a number of different people and opinions differ wildly as to how different the two approaches really are. A Google search will reveal the same thing, with numerous blog posts and questions on Stack Overflow about the topic. In my mind, a well implemented layered architecture isn't that different to a hexagonal architecture. They are certainly conceptually different but this isn't necessarily apparent from the typical implementations that I see. And that raises another interesting question: is there a canonical ports & adapters example out there? Of course, module systems (OSGi, Java 9, etc) change the landscape because they allow us to differentiate between public and published types. I wonder how this will affect the code we write and, in particular, whether it will allow us to build more modular monoliths. Feel free to leave a comment or tweet me @simonbrown with any thoughts.
Regular readers will already know about Structurizr - a set of open source libraries to create a software architecture model as code, plus a SaaS product to visualise those models. Having created and helped create a number of models with Structurizr now, I've noticed an interesting side-effect. In the absence of architectural information being present in the code, the power of using something like Structurizr to define a software architecture model using code is in extracting information algorithmically, by codifying the rules that you've ultimately used to structure your codebase.
Let me give you an example. Imagine you're building a web-MVC web application in Java, C#, etc and you have a tens or hundreds of controller classes, each of which uses a number of other components to implement some functionality. Drawing a single diagram to visualise the static structure of the entire web application is a bad idea because it shows too much information. A better approach is to create one view per vertical slice, where there could be one vertical slice per web controller. This results in smaller, simpler diagrams like this.
So far so good, and this is relatively easy to do using static analysis techniques. But you'll notice this diagram includes an "Authenticated User", which isn't part of the code itself. This raises the question of how the user ends up getting included on the diagram. There are a number of options:
The ability to codify the rules you've used to organise the controllers in your codebase obviously depends on how much thought you've put into doing this. For example, did you dump all of these controller classes into a single package or namespace without giving it much thought at all? Or perhaps you took Martin Fowler's advice and modularised further, creating one package/namespace per functional area or aggregate root, for example. Another possibility is that you grouped controllers together based upon whether unauthenticated users, authenticated users or other software systems are using them. Organising your code well provides you with another angle to extract architectural information, because you can codify rules such as, "the Anonymous User uses all controllers in the com.mycompany.mywebapp.unsecured package/namespace".
With hindsight this is fairly obvious, but we often don't put enough thought into how we organise our code, possibly because we perceive that it doesn't actually matter that much and modern IDEs provide powerful ways to navigate large and/or complex codebases. Trying to codify the rules used to organise a codebase certainly gets you thinking, and often refactoring too.
The initial version of Structurizr was targeted at the Java ecosystem (see "Structurizr for Java"), for no other reason than it's what I'm most familiar with. Although this works for a good portion of the organisations that I visit when doing training/consulting, an equally sized portion use the Microsoft stack. For this reason, I've put together Structurizr for .NET, which is more or less a direct port of the Java version, with some automatically generated code from Swagger used as a starting point. It's by no means "feature complete" yet, especially since none of the component finder code (the part that extracts components automatically from a codebase) is present, but there's enough to create some basic diagrams. Here's some example code that creates a software model for the "Financial Risk System" case study that I use in my workshops.
It creates the following Context, Container and Component diagrams.
I'm pleased to say I'll be in the United States next month for the DevNexus 2016 conference that is taking place in Atlanta, GA. In addition to a number of talks about software architecture, I'll also be running my popular "The Art of Visualising Software Architecture" workshop. Related to the (free) book with the same name, this hands-on workshop is about improving communication and specifically software architecture diagrams. We'll talk about UML and some anti-patterns of "boxes and lines" diagrams, but the real focus is on my "C4 model" and some lightweight techniques for communicating software architecture. The agenda and slides for this 1-day workshop are available online. I hope you'll be able to join me.
Happy new year and I wish you all the best for 2016. My first trip of the year starts next week and I'll be doing some work in Shenzhen, China. As a result, I'll also be in Hong Kong on January 15th, presenting "The Art of Visualising Software Architecture" at a meetup organised by Agile Hong Kong. You can register on the Meetup page. See you there!
p.s. If anybody would like a private, in-house 1-day software architecture sketching workshop on the 15th, please drop me a note.
Last week I gave a presentation titled "2015 - A CyberSecurity Year" to the London Java Community's Open Conference. I like to present at the LJC's Open Conference on whatever topic has occupied the majority of my time in the previous year. This is partly because it's always advisable to "present on what you know" but also as a cathartic exercise to vent my frustrations! The slides can be found here but won't make much sense without the following context.
This year a huge amount of my time has been spent on Cybersecurity concerns as 2015 was the year these issues were forced into everyone's mind. The threats have been increasing for several years but many high profile (and often salacious) events mean that the press, and therefore the public, have realised this is a serious issue. The first part of my presentation described what had happened over the last few years to cause the current situation.
Once the press and the public have a concern, the politicians will pick up on it and this means... laws, regulation, 'guidelines' and consequences. The second part of the presentation discussed the large range of regulators and regulations that have been (and are still being) created. These can be complex, incomplete and sometimes contradictory. I only touched the surface of what is happening. Interestingly a few of the people watching had similar concerns and experiences but many seemed unaware of even the most basic provisions of the Data Protection Act - I suspect this could be a HUGE business risk in the next few years.
These concerns have led to an increase in actual and planned expenditure (including large announcements from governments) but many in the group expressed doubts on how effectively they would be spent.
Lots of money means... lots of companies offering products and services! We spent a while discussing some of these and again, there was concern about their maturity and effectiveness.
So to bring this back on topic! Security (whether at application, system or data level) is a highly complex quality attribute. It is also constantly changing. A good architecture will take the current security concerns into account and provide foundations for not only providing this now but also for solving future issues. You not only have to address the threat but also do this is a legally compliant way. It is possible to be secure but still in breach of the law.
It is also a concern throughout the system and cannot be considered in isolation. If you are writing an application you need to think about all the services you rely upon, the sources and destination of your data and most importantly the people using it. Your developers, system administrators, database administrators and operational teams need to communicate with each other on these issues.
Good luck, I'm sure it'll all be different by the end of 2016!
If you've ever worked on a codebase that's more than just a sample application, you'll know that understanding and navigating the code can be tricky, certainly until you familiarise yourself with the key structures within it. Once you have a shared vocabulary that you can use to describe those key structures, creating some diagrams to describe them is easy. And if those structures are hierarchical, your diagrams become maps that you can use to navigate the codebase.
If you open up something like Google Maps on your smartphone and do a search for Jersey, it will zoom into Jersey. This is great if you want to know what's inside Jersey and what the various place names are, but if you've never heard of Jersey it's completely useless. What you then need to do is pinch-to-zoom-out to get back to the map of Europe, which puts Jersey in context. Diagrams of our software should be the same. Sometimes, as developers, we want the zoomed-in view of the code and at other times, depending on who we are talking to for example, we need a zoomed-out view.
A feature that has been built into Structurizr is that you can link components on a component diagram to code-level elements, which provides that final level of navigation from diagrams to code. You can try this yourself on the software architecture diagrams for the Spring PetClinic application.
Whatever tooling you use to create software architecture diagrams though, make sure that your diagrams reflect real structures in the code and that the mapping between diagrams and code is simple. My FREE The Art of Visualising Software Architecture ebook has more information on this topic.
I presented a new version of my "Software architecture as code" talk at the Devoxx Belgium 2015 conference last week, and the video is already online. If you're interested in how to communicate software architecture without using tools like Microsoft Visio, you might find it interesting.
The slides are also available to view online and download. Enjoy!
As you may have seen on Twitter, I've been mulling over an idea for a new book, which I'm pleased to say is going to happen. It's currently titled "The Art of Visualising Software Architecture" and, as the title suggests, it will focus on the visual communication of software architecture through diagrams.
The core of the book is my C4 software architecture model and although this is covered in my existing Software Architecture for Developers book, I want to create a single resource related to this topic because I still see effective communication of software architecture as a huge gap across the software development industry. You'll notice that the title of this book includes the word "art". I've seen a number of debates over the years about whether software development is a craft or an engineering discipline. Although I think it *should* be an engineering discipline, I believe we're a number of years away from this being a reality. So while this book won't present a formalised, standardised method to communicate software architecture, it will provide a collection of ideas and techniques that thousands of people across the world have found useful.
I also want to include a number of other topics and answers to frequently asked questions that I get during my software architecture sketching workshops, including some of the blog posts I've written recently such as Help, my diagram doesn't fit on one page! and Diff'ing software architecture diagrams again, for example. I'm also going to include more discussion about notation, the various uses for diagrams, the value of creating a model and tooling. Structurizr will be in there too.
Thanks very much for all of the support so far on this; the tweets/e-mails I've had are telling me that this is the right decision. Since it's not going to be a long book and initial drafts may include some text copied verbatim from my "Software Architecture for Developers book", I'm going to make this available via Leanpub using their variable pricing model ... with a starting price of free, certainly for a while anyway. It's a work in progress, but please feel free to grab a copy from Leanpub if you're interested. Thanks very much!