Separation of Concerns

Separation of concerns is defined as “a design principle for separating a computer program into distinct sections such that each section addresses a separate concern.” 1

Separation of concerns is the most powerful principle of design in my own work. I apply it everywhere.

The simple colloquial description of separation of concerns is “One class, one thing. One method, one thing.” It’s a nice soundbite, but that doesn’t give the functional programmers a free pass to ignore it.

This is about clarity and focus in our code and systems. It is one of the key enabling techniques to help us improve the modularity, cohesion, and abstraction in the systems that we create and, as a result, help us reduce the coupling to an effective minimum.

Separation of concerns also operates at all levels of granularity. It is a useful principle at the scale of whole systems as well as at the level of individual functions of a system.

Separation of concerns is not really the same kind of idea as cohesion and modularity. These two are properties of code, and while we can speak of code as having a “good separation of concerns,” what we are really saying is that the “stuff that is unrelated is far apart, and the stuff that is related is close together.” Separation of concerns is really a specific take on modularity and cohesion.

Separation of concerns is primarily a technique that we can adopt that helps us reduce coupling and improve the cohesion and modularity of our code and systems.

  1. Source: Wikipedia, https://en.wikipedia.org/wiki/Separation_of_concerns

That does, sort of, downplay its importance to my approach to design, though. Separation of concerns is a fundamental driver of good design choices for me. It allows me to keep the code and architecture of the systems that I create clean, focused, composable, flexible, efficient, scalable, and open to change, as well as lots of other good things, too.

Swapping Out a Database

When we built our financial exchange, we adopted the engineering disciplines outlined in this book. In fact, this experience is what made me want to write this book. Our exchange was fantastic—the best large-system code base that I have ever worked on or seen.

We took a strict approach to separation of concerns from individual functions all the way to our enterprise system architecture. We could write business logic that knew nothing at all about its surroundings, was completely testable, didn’t make any remote calls that it was aware of, didn’t record any data that it was aware of, didn’t know the addresses of its collaborators, and didn’t worry about its own security, scalability, or resilience.

These services could work like this because all of these behaviors were looked after elsewhere; they were other “concerns” of the system. The pieces of behavior that provided those services to the core logic didn’t know anything about the business that they operated in and didn’t know what the code for which they provided these services did.

As a result, a domain-focused service in this system was secure, persistent, highly available, scalable, resilient, and very high-performance by default.

One day, we decided that we didn’t like the commercial terms that we had with our relational database vendor. We used this database to store some of the contents of our data warehouse, a large data store that was growing rapidly and that stored historical details of order history and other business-critical values.

We downloaded one of the open source relational database management systems (RDBMSs), copied it to our repository for such dependencies, scripted its deployment, and made a few simple changes to the code that interacted with the RDBMS. This was simple because of the separation of concerns in our architecture. We then submitted the change to our continuous delivery deployment pipeline. A couple of tests failed; we tracked down the error and fixed the problems and then committed the new version to the pipeline. All the tests in our deployment pipeline passed on this second attempt, so we knew that our change was safe to release. Our changes were deployed into production the next time the system was released a few days later.

This whole story took a single morning!

Without good separation of concerns, this would have taken months or years and probably wouldn’t even have been contemplated as a result.

Let’s look at a simple example. In the previous chapter, I showed three examples of code solving the same problem; Listing 11.1 shows them again.

Listing 11.1 Three Separation of Concern Examples

Click here to view code image

def add_to_cart1(self, item):
    self.cart.add(item)
    conn = sqlite3.connect(‘my_db.sqlite')
    cur = conn.cursor()
    cur.execute('INSERT INTO cart (name, price) 
    values (item.name, item.price)’)
    conn.commit()
    conn.close()
    return self.calculate_cart_total();
def add_to_cart2(self, item):
    self.cart.add(item)
    self.store.store_item(item)
    return self.calculate_cart_total();
def add_to_cart3(self, item, listener):
    self.cart.add(item)
    listener.on_item_added(self, item)

In the previous chapter, we discussed these in the context of cohesion, but the principle that I used to achieve a more cohesive result was separation of concerns.

In the first, bad example, add_to_cart1 , the separation is nonexistent. This code bundles together the core focus of the function, adding something to a cart, with the esoteric detail of how things are stored in a relational database. It then, as a side effect, calculates some kind of total. Nasty!

The second example, add_to_cart2 , is a considerable step forward. Now we are initiating the storage but don’t care how that works. We could imagine that the “store” was supplied to the class and could be anything. This code is considerably more flexible as a result. It still knows that storage and cart-total calculation are involved, though.

The third example represents a more complete separation of concerns. In this example, the code executes the core behavior, adding something to the cart, and then merely signals that something was added. This code doesn’t know and doesn’t care what happens next. It is entirely decoupled from storage and total calculation. This code is considerably more cohesive and more modular as a result.

Clearly, as with any design decision, there is choice here. I would argue that add_to_cart1 is just bad. Separation of concerns would rule it out. The guiding principle is that this is a mix of essential and accidental complexity. That is, how and where we store something is not germane to the core shopping-cart behavior that we are trying to create. We want a clear line, a separation, between code that deals with essential and code that deals with accidental complexity.

The difference between the second two examples is more nuanced. This is more of a matter of context and choice. My personal preference is strongly in favor of add_to_cart3 . This is the most flexible solution of all. I may or may not choose to achieve my separation with a method-injected listener like this, but I very much like that I have removed the concept of storage from my core domain.

This is the code that I would usually write. To my mind, version 2 of add_to_cart is still confusing concerns. I certainly think that store_item is a better abstraction than some connection and SQL stuff, but the concept itself is still in the realm of accidental complexity. If you put something in a real shopping cart, you don’t then need to “persist” it!

Version 3 gives me the greatest freedom of choice, at little real penalty. A valid criticism of this approach is that you can’t see here that storage may be going on, but that is not really what matters here, in this moment, for this piece of code. Storage is a side effect of how our computer works, not a core behavior of adding something to a shopping cart. In the third example, we can clearly see that when an item is added, and see that something else may be happening; we just don’t care what. If we do care, we can go and look.

Think for a moment about the testability of each of these methods. Version 1 will be horrible to test. We will need a database, so the test will be difficult to establish and probably extremely fragile and slow; either the database will be shared and liable to change outside of the test, or it will be created during the setup of the test, and each test run will be very slow to execute. Both of the other two versions can be tested easily and efficiently with fakes.

The primary argument against version 3 is that it is less clear what is going on. I certainly agree that clarity is a virtue in code. Actually, though, this is really just a matter of context. I am looking at the code here that is responsible for adding an item to a cart. Why should it know what happens next?

This focus on separation of concerns has helped us improve the modularity and cohesion of this code. Depending on the degree to which the collaboration of several parts matter—listeners that store the results or calculate totals, for example—we can test the correct establishment of those relationships elsewhere.

So the “whole picture” is obscured only because we are looking in the wrong place. If we were to take that rather naive view of the world, then shouldn’t the generic collection that we are using to represent our cart also know about storage and totals? Of course not!

One of the reasons that I value separation of concerns so highly as a guiding principle is because it reminds me to keep my focus small. I feel proud of code that I have written when you can look at each part and understand what that part does without thinking too hard about it. If you have to study it for more than a handful of seconds, I have failed. Now you may have to understand how that part is used by other parts, but those other parts will have their own concerns to deal with, and I ideally express them as clearly.

Dependency Injection

An extremely useful tool in achieving a good separation of concerns is dependency injection . Dependency injection is where dependencies of a piece of code are supplied to it as parameters, rather than created by it.

In our by now slightly overused example, in add_to_cart1 the connection to the database is explicitly created and opened within the method. This means that there is no opportunity to use an alternative. We are tightly coupled to this specific implementation, even to this specifically named instance of the database. If the store in version 2 is passed in as a constructor parameter, then immediately this represents a step-change in flexibility. We can supply anything that implements store_item .

In version 3 of our add_to_cart method, the listener could be anything that implements on_item_added .

This simple change in the relationship between the behaviors of this code is significant. In the first case, version 1, the code creates everything that it needs, so it is deeply coupled to a single, specific implementation. This code is inflexible by design. In the others, the code is a collaborator with other components of the system, so it knows, and cares, little about how they operate.

Dependency injection is often misunderstood as the function of a tool or framework, but this is not the case. Dependency injection is something that you can do in most languages, certainly in any OO or functional language, natively, and it is a powerful approach to design. I have even seen it used, to very good effect, in Unix shell scripts.

Dependency injection is a fantastic tool to minimize coupling to an appropriate, useful level, but it is also an effective way to form a line of demarcation between concerns. I will point out again how interlinked all these ideas are. This is not because of repetition, but rather that we are describing some important, deep properties of software and software development; therefore, as we approach those problems from different directions, they inevitably intersect.

Separating Essential and Accidental Complexity

An effective route into improving the quality of our design is to aim to separate concerns in a specific way—that is, to separate the essential complexity of our systems from the accidental. If the concept of “essential and “accidental” complexity is new to you, these are important ideas first described in Fred Brooks’ famous paper “There is No Silver Bullet,” mentioned earlier in this book.

The essential complexity of a system is the complexity that is inherent in solving the problem that you are trying to solve, how to calculate the value of a bank account, how to total the items in a shopping cart, or even how to calculate the trajectory of a spaceship, for example. Addressing this complexity is the real value that our system offers.

The accidental complexity is everything else—the problems that we are forced to solve as a side effect of doing something useful with computers. These are things like persistence of data, displaying things on a screen, clustering, some aspects of security…in fact anything that is not directly related to solving the problem at hand.

Just because it is “accidental” does not mean that it is unimportant; our software is running on a computer, so dealing with the constraints and the realities of that is important, but if we built a system that was fantastic at dealing with accidental complexity but didn’t have any essential complexity, it would, by definition, be useless! So, it is in our interests to work to minimize, without ignoring, accidental complexity.

An effective approach to improving our designs through separation of concerns is to focus very clearly on separating the concerns of the accidental and essential complexities of our systems.

I want the logic of my system that cares about how to drive a car to be separate from the logic that knows how to display information on a screen, the logic that knows how to evaluate a trade to be separate from how that trade is stored or communicated.

This may or may not seem obvious, but it is important, and, subjectively, it doesn’t seem to me to be how most code is written. Most of the code that I see people write decidedly conflates these two different classes of responsibility. It is common to see business logic mixed with display code and the details of persistence in the midst of the logic that deals with, or that should deal with, the core domain (the essential complexity) of the system.

This is yet another area where focusing on the testability of our code and systems can be a big help in improving our design.

Listing 10.1 demonstrated this clearly. This code is not really testable in any but the most naively complex way. Sure, I could write a test that first created a file at a specific location on disk called words.txt and then run the code and look for a result in another file at a specific location called sorted.txt , but this would be slow, annoyingly complex, and so coupled to its environment that I could trivially break the test by renaming the files or moving their location. Try running this test in parallel with itself, or something closely related, and you will quickly face some unpleasant problems!

The majority of the work going on in Listing 10.1 is not even vaguely related to the behavior of the code that matters. This is nearly all accidental complexity in the heart of the code that should be focused on doing something more important—in this case sorting a collection of words.

Listing 10.2 improved the cohesion but is still not testable as a unit. It shares the same problems as Listing 10.1 in this regard.

Listing 11.2 is an example of attempting to improve this code purely from the perspective of separating the accidental from the essential complexity. I wouldn’t really pick names like “essential” or “accidental” for real code; they are just to make the example clearer.

Listing 11.2 Separating Accidental and Essential Complexity

Click here to view code image

public interface Accidental
{
    String[] readWords() throws IOException
    boolean storeWords(List<String> sorted) throws IOException
}
public class Essential
{
    public boolean loadProcessAndStore(Accidental accidental) throws IOException
    {
        List<String> sorted = sortWords(accidental.readWords());
        return accidental.storeWords(sorted);
    }
    private List<String> sortWords(String[] words)
    {
        List<String> sorted = Arrays.asList(words);
        sorted.sort(null);
        return sorted;
    }
}

Assuming that we implement the accidental complexity functions outlined in our “Accidental” interface in Listing 11.2, this code does exactly the same things as Listings 10.1 and 10.2, but it is better. By separating the concerns—in this case using the “seam” between the accidental complexity and the essential complexity of the problem that we are solving—we have improved things considerably. This code is easier to read, more focused on the problem that matters, and considerably more flexible as a result. If we wanted to supply “words” from somewhere other than a file in a specific location on a specific device, we can. If we want to store the sorted words somewhere else, we can.

This is still not great code. We could further improve its separation of concerns to improve its focus and decouple it more in terms of readability, as well as at the technical level.

Listing 11.3 shows something a bit closer; we could certainly debate some of my naming choices, which would be more context dependent, but purely from the perspective of separation of concerns, I hope that you can see a very big difference between the code in Listing 10.1 and Listings 11.2 and 11.3. Even in this simple sample, we improved the readability, testability, flexibility, and utility of this code by following these design principles.

Listing 11.3 Removing Accidental Complexity with Abstraction

Click here to view code image

public interface WordSource
{
    String[] words();
}
public interface WordsListener
{
    void onWordsChanged(List<String> sorted);
}
public class WordSorter
{
    public void sortWords(WordSource words, WordsListener listener)
    {
        listener.onWordsChanged(sort(words.words()));
    }
    private List<String> sort(String[] words)
    {
        List<String> sorted = Arrays.asList(words);
        sorted.sort(null);
        return sorted;
    }
}

The separation of essential and accidental complexity is a good starting point to help us get to code with a better separation of concerns. There is a lot of value in this approach, but it is the low-hanging fruit. What about other mixed concerns?

Importance of DDD

We can also look to guide our designs from the perspective of the problem domain. If we take an evolutionary, incremental approach to design, we can work in ways that allow us to keep a sharp look out for those moments when we may identify new concerns—concerns that may otherwise be inappropriately conflated in our designs.

Listing 11.4 shows some Python code. In it, I try to create a version of the children’s game Battleship, in which we try to sink our opponent’s fleet.

I have come to the point in my design where I am beginning to question it.

Listing 11.4 Missing a Concept

Click here to view code image

class GameSheet:
    def __init__(self):
        self.sheet = {}
        self.width = MAX_COLUMNS
        self.height = MAX_ROWS
        self.ships = {}
        self._init_sheet()
    def add_ship(self, ship):
        self._assert_can_add_ship(ship)
        ship.orientation.place_ship(self, ship)
        self._ship_added(ship)

In my GameSheet that represents the playing area, the grid of squares, of the game, I have come to the point where I want to add a ship to the sheet.

I was using Test-Driven Development (TDD) to create this code, and at this point I had a growing series of tests in GameSheetTest focused on the complexities of adding a ship. Out of 11 tests, 6 of them were focused on testing whether I was allowed to place a ship onto the GameSheet . I had begun adding validation code to the GameSheet to verify my additions, and I had about 9 or 10 lines of code in three extra functions.

I was feeling uneasy about my design of this code and of the tests that supported it. Both were growing in size and complexity, not by much, but enough to make me start looking for what was wrong. Then I realized that I was making a separation of concerns mistake. My problem was that my design was missing an important concept completely.

My GameSheet was responsible for the position of the ships and the rules of the game. Having an “and” in the description of a class or a method is a warning sign. It says that I have two concerns rather than one. In this case, it quickly seemed obvious to me that I was missing the concept of “rules” in my implementation. I refactored the code and the tests, extracting a new class called Rules . Listing 11.5 shows how the addition of Rules simplifies things.

Listing 11.5 Listening to the Code

Click here to view code image

class GameSheet:
    def __init__(self, rules):
        self.sheet = {}
        self.width = MAX_COLUMNS
        self.height = MAX_ROWS
        self.rules = rules
        self._init_sheet()
    def add_ship(self, ship):
        self.rules.assert_can_add_ship(ship)
        ship.orientation.place_ship(self, ship)
        self._ship_added(ship)

This immediately simplified the GameSheet . It removed the need for the sheet to maintain a collection of Ships , and it removed nine or ten lines of validation logic that was only the beginning of the evolution of my code focused on validating compliance with the rules.

Ultimately, this change gave me more flexibility in my design for the future, allowing me to better test the GameSheet logic and the Rules independently of one another and, potentially, as a side effect, opened the door to having this code work with different versions of the Rules one day. I didn’t worry about what those rules might be. I didn’t do any extra work to support some imaginary future new rules, but there was now a “seam” in my code that could possibly prove useful in the future while, in the pragmatic real world of the present, it allowed me to better test my code and improved my design. All this was driven by a simple focus on separation of concerns.

Using the problem that you are solving to help you define sensible lines of demarcation in your code is really the essence of separation of concerns. This is true at various levels of granularity. We can begin with bounded contexts to identify course-grained modules (or services) in our design and then work to refine our design over time as we learn more about the problem that we are solving and gain more insight into the readability, or otherwise, of our code.

One of the keys here is to try to maintain a very low tolerance for complexity. Code should be simple and readable, and as soon as it begins to feel like hard work, you should pause and start looking for ways to simplify and clarify the part in front of you.

In the example outlined in Listings 11.4 and 11.5, the thing that started me worrying about my design was probably down to only ten lines of code and a few test cases that I later decided were in the wrong place. This is one of the reasons that I value separation of concerns quite so highly. It provides me with a mechanism to, very early in the process, detect problems that will, if I don’t react to them, lead to reduced modularity and poor cohesion in my designs.

Testability

This approach to incrementally evolving the design of your code, while keeping an eye out for poor separation of concerns, is reinforced through testing. As I have already described, dependency injection can help us improve our designs, but an even more powerful, maybe an even more fundamental, tool to help to establish an effective separation of concerns is testability.

We can use the testability of the systems that we create to drive quality into them in a way that little else, beyond talent and experience, can do.

If we work to ensure that our code is easy to test, then we must separate the concerns or our tests will lack focus. Our tests will also be more complex, and it will be difficult to make them repeatable and reliable. Striving to control the variables so that we can test encourages us to create systems that demonstrate the properties of high quality in software that we value: modularity, cohesion, separation of concerns, information hiding, and loose coupling.

Ports & Adapters

Our aim in focusing on separating concerns is to improve the modularity and cohesion of our systems. This, in turn, makes our systems overall less tightly coupled. Managing the coupling in our systems appropriately should be one of the primary focusses of our designs, and this is true at every level of granularity.

One level where this is perhaps most clearly evident, and of value, is at those seams in our code where one “concern” interacts with another. These are places in our systems where we should always take more care.

Let’s look at a simple example (see Listing 11.6). Here we have some code that wants to store something—in this case in an Amazon AWS S3 bucket. We have some code that processes whatever it is that we want to store and some code that invokes the storage itself, which is a decent start for separating the concerns of processing and storage.

For this code to work, there will have been some setup somewhere to initialize the s3client so that it knows the necessary details of the account that owns the bucket and so on. I haven’t shown that code here, on purpose; I am sure that you can imagine several different ways that s3client arrived at this point. Some of these ways demonstrate better or worse separation of concerns. In this case, let’s just focus on what we have in this function.

Listing 11.6 Storing a String in S3

Click here to view code image

void doSomething(Thing thing) {
    String processedThing = process(thing);
    s3client.putObject("myBucket," "keyForMyThing," processedThing);
}

As it stands, the code in Listing 11.6 is written from two different perspectives. We are used to seeing code like this all the time, but let’s think about it for a moment. Here we have two very different focuses and two very different levels of abstraction all within two lines of code.

The first line is focused on doing something that makes sense in the world of the function or method, perhaps “process (thing)’” makes sense in a business context; it doesn’t really matter, except that this is, presumably, the focus, the essential part, of this code. This is the job that we want done, and it is written from that perspective. The second line is, err, alien. It is an interloper that has dumped accidental complexity into the heart of our logic.

One take on cohesion is that within a particular scope, the level of abstraction should remain consistent. So what if we improved the consistency here? Listing 11.7 is a big improvement in this respect, even if all that we have done is rename a class and a method.

Listing 11.7 Storing a String in S3 via a Port

Click here to view code image

void doSomething(Thing thing) {
    String processedThing = process(thing);
    store.storeThings("myBucket," "keyForMyThing," processedThing);
}

Now there are some implications as a result of the change from Listing 11.6 to Listing 11.7. By making the “invocation to store” more consistent with the other ideas in this function, we have increased the abstraction. We have also started to push our design in a different direction.

Remember the code that I didn’t show; by making this one simple change, I have made a bunch of implementations for that initialization wrong. If I abstract storage in this way, it makes no sense at all for all of that initialization to be within the scope of this class or module. It’s much better to externalize it completely.

So now I am going to hide all of that initialization somewhere else. That means I can test it, in abstract, separate from this code. It means that if I choose to use dependency injection to supply my store, I can test this code without the need for a real store. It also means that I can choose where I want to store things outside of this code, supplying different kinds of stores in different contexts so my code is more flexible.

You can think of the new abstraction as a port , or a vector through which information flows. Whether or not you decide to make the port polymorphic is entirely up to you and the circumstances in your code, but even where you don’t, this code is better. It is better because you have improved the separation of concerns, improved the cohesion by maintaining a more consistent level of abstraction, and improved both its readability and maintainability.

The concrete implementation of this port is an adapter that acts as a translation service, translating ideas from, in this example, the context of “things” to the context of “AWS S3 Storage.”

After this change, our code doesn’t know anything about S3; it doesn’t even know that S3 is being used.

The key idea here is that the code is written from a more consistent frame of reference. It maintains that more consistent abstraction.

What I have described here is sometimes called the Ports & Adapters pattern, also sometimes referred to as hexagonal architecture when applied at the level of a service or subsystem.

The value of this, in design, is very significant. It is almost never the case that your code cares about every single detail of an API that it consumes. You nearly always deal with a subset of such APIs. The port that you create only needs to expose the minimal subset that you choose to use, so it will nearly always be a simpler version of the API that you are interacting with.

The trouble with writing a book that talks about code is that to convey ideas, the code examples need to be small and simple, or the ideas get lost in the complexity of the code. But what about when you are trying to show the improvement in simplicity?

So bear with me. Imagine that we had a whole system written along the lines of Listing 11.6: tens, hundreds, maybe even thousands of interactions through an s3client . Then Amazon upgrades the interface to the S3 service, or at least the Java client library. Version 2 has a different programming model, so now we have to go and change tens, hundreds, or thousands of lines of code to take advantage of the new client library.

If we have created our own abstraction, our own Port & Adapter for S3, that does just, and only just, what our code needs, we can probably use that in more than just one place in the code. Maybe we use it everywhere, maybe there are some cases that are more complex, and maybe we have a different, separate Port & Adapter for those cases. Either way, we have significantly reduced our maintenance effort. We could completely rewrite the adapter to use the new client library. It wouldn’t affect the code that uses it at all.

This approach embodies many of the goals of good design. By working to manage complexity, we also insulate our code against change—even unexpected or unpredictable change.

When to Adopt Ports & Adapters

When people discuss the Ports & Adapters approach, they are usually discussing it in the context of a translation layer at the boundaries between services (or modules).

This is good advice. In his book Domain Driven Design , 2 Eric Evans recommends:

Always translate information that crosses between Bounded Contexts.

In designing a system from services, I, and others, advise that we should aim to align our services with a bounded context. This minimizes coupling and improves the modularity and cohesion of our services.

Combined, these two pieces of advice suggest a simple guideline of “Always translate information that flows between services,” or to put it another way, “Always communicate between services using Ports & Adapters.”

When I started writing the previous sentence, I first wrote “rule” rather than “guideline” and then quickly corrected myself. I can’t, in good conscience, describe this as a rule, because there are sometimes corner cases that break the rule. However, my strong advice is to assume, as a default position, that all information exchanges between services will be translated via an adapter, whatever the technical nature of the API.

  1. Domain Driven Design is a book by Eric Evans describing how to model the problem domain in software as a guiding principle in design. See https://amzn.to/2WXJ94m .

This doesn’t mean the adapter needs to be lots of code or complex, but from a design perspective, each service or module should have its own view of the world and should defend that perspective. If information is sent that breaks that view, that is a serious problem for the code.

We can protect our code two ways, and we can use an adapter that translates things into our worldview as they arrive at the edges of our system, allowing us to validate our inputs to the degree to which we care about them. Or we can wrap up stuff that we don’t trust and ignore it so that we can protect our systems from dubious external changes.

If we are writing a messaging system of some kind, for example, there are things that we need to know, and there are things that we should certainly not know.

We probably need to know who sent a message and where it is going. We probably need to know how big the message is and maybe whether we should retry it if there is a problem. We should certainly not know what the message is saying! That would immediately couple the technicalities of messaging to the semantics of the conversation that the messaging is being used for and would be very poor design.

This may or may not seem obvious, but I also see a lot of code that makes precisely this kind of mistake. If I were building a messaging system, I would “wrap up” the content of the message in a packet of some kind that insulates the messaging system from the content of the packets, the messages themselves.

What Is an API?

This starts to get into a bit of design philosophy: what is an API? I would argue for a fairly practical definition:

An application programming interface (API) is all of the information that is exposed to consumers of a service, or library, that exposes that API.

This is different from what some developers think of when we use the term API.

There has been a morph over time in what the term “API” means. In part, this is probably due to the success of the REST approach to creating services. It is common, at least in informal conversations with developers, that the term “API” is used as a synonym for “Text over HTTP.” This is certainly one form of API, but it is only one; there are many more.

Strictly any means of communication between different bits of code, meant to support programming of some kind, is an API. This is where it is important to think about the information that our code interacts with.

Imagine, for a moment, a function that takes a binary stream of data as an argument. What is the API?

Is it only the signature of the function? Well, maybe, if the function treats the binary stream as a black-box and never looks inside the stream, then yes, the signature of the function defines its coupling with its callers.

However, if the function interacts with the contents of the binary stream in any way, that is part of its contract. The level of interaction defines the degree to which it is coupled, with the information in the stream.

If the first eight bytes in the stream are used to encode its length, and that is all that the function knows or cares about the stream, then the function signature, plus the meaning of the first eight bytes and how the length is encoded within them, are “the API.”

The more that the function knows of the content of the stream of bytes, the more coupled to it it is, and the greater the surface area of the API. I see many teams that ignore the fact that the data structures in its inputs that their code understands, and processes, are part of that code’s public API.

Our adapters need to deal with the whole API. If that means translating, or at least validating, the content of a binary stream of inputs, then so be it. The alternative is that our code may break when someone sends us the wrong stream of bytes. This is a variable that we can control.

Designing with the assumption that we will always add Ports & Adapters at these points of communication between modules and services is a much stronger default stance than not. Even if the “adapter” is a placeholder for the future, having that placeholder in place gives us the opportunity, should the nature of the API change in any way to cope with those changes without having to rewrite all of our code.

This is the classic model of Ports & Adapters. I recommend thinking about this at finer-grained levels, too. I don’t mean to suggest that you always write explicit translations, but the idea of trying to maintain a consistent level of abstraction within any piece of code, no matter how small (see Listing 11.6), is a good one.

As a default stance, or a guideline, I recommend that you always add Ports & Adapters where the code that you talk to is in a different scope of evaluation, such as a different repo or a different deployment pipeline. Taking a more defensive stance in these situations will make your code more testable, yet again, and more robust in the face of change.

Using TDD to Drive Separation of Concerns

I have already described how the ideas of designing to improve the testability of our code help us improve its quality, not just in the simplistic sense of “does it work,” but in the more profound sense of building the kind of quality into our products that makes them capable of ongoing maintenance and development.

If we design our code using the ideas of separation of concerns as a guiding principle, including the ideas of maintaining a consistent level of abstraction within any given, even small, context, then we leave the door open to incremental change. Even if we don’t yet know the details of how something will be communicated, stored, or interacted with in general, we can write code and make progress.

Later, as we learn more, we can use the code that we wrote in ways that we hadn’t thought of when we wrote it. This approach allows us to take a more evolutionary approach to design, growing our systems, step-by-step, as our understanding deepens, into much more sophisticated, much more capable, versions in the future.

TDD is the most powerful tool that we can wield to achieve that testability. By driving all of our development from the perspective of testing, we dramatically change the focus of our designs.

Specifically in the context of separation of concerns, our tests become more difficult to write the more that concerns are conflated within the scope of a test. If we organize our development around testing and drive our development through testing, then we are confronted much earlier in the process by the costs and benefits of our design decisions.

This faster feedback is, naturally, a good thing, allowing us the opportunity to spot flaws in our design much sooner than any other technique, apart from us just being smarter than we are, over which we can exert only a limited degree of control. There is nothing wrong with being smart, but the best way to become “smarter” is to work in smarter ways, which is really the aim of this book. TDD is one of those important “smarter ways.”

Summary

Separation of concerns is certainly an attribute of high-quality code. If you have two pieces of code that fulfil exactly the same function and one has good separation of concerns and the other doesn’t, then the first is easier to understand, easier to test, easier to change, and more flexible.

Separation of concerns is also the easiest design heuristic to adopt of the collection here.

We could debate the modularity or cohesion of some code or system. As you can see, I consider these ideas to be extremely important, but ultimately their measurement is somewhat subjective. While we can probably agree on bad examples, we’d probably struggle to, at the limit, define what ideal modularity or cohesion was.

Separation of concerns is different. If your module, class, or function does more than one thing, your concerns aren’t really separate. The result is that separation of concerns is a fantastic tool to guide us, definitively, in the direction of the design of better software.