Information Hiding and Abstraction

Information hiding and abstraction is defined as “the process of removing physical, spatial, or temporal details or attributes in the study of objects or systems to focus attention on details of greater importance.” 1

I lumped together two slightly different ideas in computer science in the title of this chapter; they are different but related, and for the purpose of thinking about fundamental principles for software engineering, they are best considered together.

Abstraction or Information Hiding

I conflate these ideas because I don’t think that the difference between the two is enough to really concern us. What I am talking about here is drawing lines, or seams, in our code so that when we look at those lines from the “outside,” we don’t care about what is behind them. As a consumer of a function, class, library, or module, I should not need, or care, to know anything about how it works, only how I use it.

Some people take a much narrower view of information hiding than this, but I don’t see that it adds anything useful. If you can’t get away from worrying about “information hiding being only about data” (it’s not), then whenever I say “information hiding,” think “abstraction.”

If you can’t get away from thinking “abstraction” means only “creating abstract concept-objects,” then while that is part of the definition, it is not what I mean, so maybe think “information hiding.”

  1. Source: Wikipedia, https://en.wikipedia.org/wiki/Abstraction_(computer_science)))

The information that I am hiding is the behavior of the code. It includes implementation detail as well as any data that it may or may not use. The abstraction that I present to the outside world should achieve this trick of keeping secrets from other parts of the code.

It should be obvious that if our aim is to manage complexity so that we can build more complex systems than we can comfortably hold inside our heads, then we need to hide information.

We’d like to be able to focus on the work/code in front of us without worrying about what is going on elsewhere and how stuff that we don’t need to care about right now works. This seems fundamental, but there is a lot of code in the world that does not look like this. Some code is fragile to change, where change in one place affects other parts of the code. There is code where the only way to make progress is to be so smart that you understand how most of the system works. That is not a scalable approach!

What Causes “Big Balls of Mud”?

We sometimes call these difficult to work on codebases big balls of mud . They are often so tangled, so convoluted, that people are scared to change them. Most organizations, particularly bigger organizations, that have built software for any length of time will own some tangled code like this.

Organizational and Cultural Problems

The causes are complex and diverse. One of the most common complaints that I hear from software developers and software development teams is “my manager won’t let me XXX,” where “XXX” is either “refactor,” “test,” “design better,” or even “fix that bug.”

There are certainly some unpleasant organizations in the world. If you work somewhere like that, my advice is to seek better employers. However, in the vast majority of cases, this complaint is simply not true, or at least not entirely true. At worst this is an excuse. I dislike blaming people, though, so a more charitable interpretation is that this is based on an important misunderstanding.

The first thing to say is why do we, as software developers, need to ask for permission to do a good job? We are the experts in software development, so we are best placed to understand what works and what doesn’t.

If you hire me to write code for you, it is my duty to you to do the best job that I can. That means I need to optimize my work so that I can reliably, repeatably, and sustainably deliver code over a long period of time. My code needs to solve the problem that I am faced with, and it needs to fulfill the needs of my users and ambitions of my employers.

So, I need to create code that works, but I also need to sustain my ability to do so over time, repeatably and reliably. I need to maintain my ability to modify the code as I learn more about the problem that we are solving and the system that we are developing.

If I were a chef preparing a meal in a restaurant, I could probably prepare one meal more quickly if I decided not to clean up my tools and work area when I finished. That will probably work for one meal. It may even work for two meals; it would be disgusting, but it may work. If I worked like that all of the time, though, I’d get fired!

I’d get fired because I’d give the patrons of the restaurant food poisoning. Even if I didn’t get fired, by the time I got to the third meal, I would be far slower and less productive because the mess that I had made would get in the way of my work. I’d have to clear a work area and the tools I was using for every task. I’d have to struggle with tools that were no longer sharp enough, and so on. Does this sound familiar?

If you hired me as a chef, you would never say, “you have permission to sharpen your knives” or “it is your responsibility to clean your work area,” because as a professional chef, you, and I, would assume that those things are a fundamental part of being a professional. As a chef, that would be part of my duty of care .

As software professionals, it is our duty to understand what it takes to develop software. We need to own the responsibility for the quality of the code that we work on. It is our duty of care to do a good job. This is not altruistic; it is practical and pragmatic. It is in the interest of our employers, our users, and ourselves.

If we work to create and maintain the quality of our code, our employers will get the new features that they want more efficiently. Our customers will get code that makes more sense and is more usable, and we will be able to make changes without being constantly nervous of breaking things.

This matters for a variety of reasons, not the least because the data is very clear. 2 Software is not a game of short-term wins. If you are dropping testing, avoiding refactoring, or not taking time to find more modular, more cohesive designs to achieve some short-term delivery target, you are going more slowly, not faster .

It is reasonable for an organization creating software to want to do it efficiently. There is an economic impact that affects all of us who work for such an organization.

If we want the organizations in which we work to thrive and for us to have a more pleasant experience while building the software that helps our organizations to thrive, then we need to work effectively.

Our aim should be to do whatever it takes to build better software faster. The data is in: the Accelerate book describes some of what it takes, and that certainly does not involve naively cutting corners in quality. The reverse is true.

One of the key findings of the “State of DevOps” report that underpins the scientific approach to analyzing the performance of software teams outlined in the Accelerate book is that there is no trade-off between speed and quality . You don’t create software faster if you do a poor job on quality.

  1. The Accelerate book describes how teams that take a more disciplined approach to development spend “44% more time on new work” than teams that don’t. See https://amzn.to/2YYf5Z8 .

So when a manager asks for an estimate for a piece of work, it is not in your interest, your manager’s interest, or your employer’s interest to cut corners on quality. It will make you go slower overall, even if your manager is dumb and thinks that it will.

I have certainly seen organizations that, either intentionally or unintentionally, applied pressure on developers to speed up. Often, though, it is developers and development teams that are complicit in deciding what “speeding up” entails.

It is usually the developers that rule out quality, not the managers or organization. Managers and organizations want “better software faster,” not “worse software faster.” In reality, even that is not the trade-off. As we have already seen, the real trade-off, over long periods of time, is between “better software faster” and “worse software slower.” “Better” goes hand in hand with “faster.” This is important for all of us to recognize and to believe. The most efficient software development teams are not fast because they discard quality but because they embrace it.

It is the professional duty of a software engineer to recognize this truth and to always offer advice, estimates, and design thoughts based on a high-quality outcome.

Don’t parse estimates and predictions to separate out the time to do a good job; assume that your managers, co-workers, and employers want you to do a good job, and do it.

There is a cost to doing work. In cooking, part of that cost is the time it takes to clean up and maintain your tools as you go. In software development, those costs are to refactor, to test, to take the time to create good designs, to fix bugs when they are found, to collaborate, to communicate, and to learn. These are not “nice to have” options; these are the foundations of a professional approach to software development.

Anyone can write code; that is not our job. Software development is more than that. Our job is to solve problems, and that requires us to take care in our design and consider the effectiveness of the solutions that we produce.

Technical Problems and Problems of Design

Assuming that we give ourselves permission to do a good job, the next question is, what does that take? That is really the theme for this book. The techniques that allow us to optimize for learning, outlined in Part II , and the techniques described in this part, combined, give us the tools that allow us to do a better job.

Specifically, in the context of avoiding and correcting big balls of mud, though, there is a mindset that is important to adopt. This is the mindset that it is a good thing, a sensible thing, to change existing code.

Many organizations are either afraid to change their code or have some kind of reverence for it that belies the reality. I would argue the reverse: if you can’t, or won’t, change the code, then the code is effectively dead. To quote Fred Brooks again:

As soon as one freezes a design, it becomes obsolete. 3

My friend Dan North has spoken about an interesting idea. Dan has a gift for capturing an idea in a clever turn of phrase. He talked about the “software half-life of a team” as a metric for quality.

Now neither I nor Dan have any data to back up this idea, but it is an interesting one. He says that the quality of the software produced by a team is a function of its software half-life—that is, the time that it takes the team to rewrite half of the software that they are responsible for.

In Dan’s model, good teams will probably rewrite half the software that they are responsible for in months; low-performing teams may never rewrite half.

Now I am pretty sure that Dan’s idea is very contextual; when he came up with this, he was working in a very good, fast-paced, financial trading team. I am equally certain that there are many teams where this rule doesn’t apply. Nevertheless, there is certainly a grain of truth here.

If we are, as I contend, a discipline foundationally rooted in our ability to learn, then when we learn new things that change our view on what is optimal for our design (whatever that means in our context), at that point, we should be able to change it to reflect our new, deeper understanding.

When Kent Beck picked a subtitle for his famous book on Extreme Programming, he chose Embrace Change . I don’t know what he had in mind when he picked that subtitle, but I have come to think that it has much wider implications than I imagined when I first read his book.

If we buy in to this fundamental philosophy that we must retain our ability to change our ideas, our teams, our code, or our technology, as we learn more, then nearly everything else that I talk about in this book follows on as a natural consequence.

Working in ways that leave the door open to us making a mistake and being able to correct it; deepening our understanding of the problem that we face and reflecting our new understanding in our design; evolving our products and technologies incrementally in the direction of success wherever, or whatever, that may be—these are all targets for good engineering in software.

To be able to do this, we need to work in small steps that are easy to undo. We need our code to be a habitable space that we can revisit, maybe months or years later, and still understand. We need to be able to make a change in one part of the code and not have it affect others. We need a way to quickly and effectively validate that our changes were safe. Ideally, we’d also like to be able to change some of our architectural assumptions as our understanding, or maybe the popularity of our system, changes.

All the ideas in this book are relevant to that, but abstraction or information hiding feels to me to represent the clearest route to habitable systems.

  1. A quote from Fred Brooks’ book Mythical Man Month , https://amzn.to/3oCyPeU

Raising the Level of Abstraction

What would it take to get a Brooksian order-of-magnitude improvement? One avenue to explore is to raise the level of abstraction of programming.

The most common theme, in this line of thinking, has been to strengthen the relationship between the high-level diagrams that we sometimes use to describe our systems. “Wouldn’t it be good if when I draw a picture of my system, I can use that picture to program my system, too?”

Over the years there have been lots of attempts at implementing this, and periodically new versions of this idea tend to crop up. At the time of writing, the current incarnation of this approach is called low code development .

However, there are several problems that seem to get in the way of this approach.

One common approach to diagram-driven development is to use the diagram to generate source code. The idea here is to use the diagrams to create the broad structure of the code, and then the detail can be filled in, by hand, by a programmer. This strategy is pretty much doomed to failure by one difficult-to-solve problem. The problem is that you are almost always going to learn more as the development of any complex system evolves.

At some point, you will need to revisit some of your early thinking. This means that your first version of your diagram and so the skeleton structure of your system is wrong and will need to change as your understanding deepens. The ability to “round-trip” or create a skeleton for your code, modify the detail by hand, change your mind, regenerate the diagram from the code, modify it, but keep the detailed changes is a tricky problem. It is the hurdle at which all such efforts, so far, have fallen.

So how about doing away with the manual coding step altogether? Why not use the diagrams as the code? This too has been tried lots of times. These sorts of systems usually demo extremely well. They look really nice and easy when building some simple, sample system.

However, there are two big problems. It is actually hard to raise the level of abstraction to a degree where you gain, by drawing pictures rather than writing code. You lose all of the benefits that, over time, we have evolved to support more conventional programming languages such as exception handling, version control, debugging support, library code, automated testing, design patterns, etc.

The first problem is the reason why these things demo so well but don’t really scale to real-world systems. The problem is that while it is easy to create a graphical “language” that lets us express simple problems succinctly, it is much more difficult to create a similar visual “language” that provides general-purpose tools that allow you to create any old piece of logic. Turing-complete languages are really built out of some extremely common but quite low-level ideas. The level of detail that we require to describe and encode a working, complex software system seems to be inherently intricate and fine-grained.

Consider the need to add a graph to a spreadsheet. Most spreadsheet programs offer tools that allow you to add a graph, err, graphically. You can select some rows and columns of data in your spreadsheet and select a picture of the type of graph that you would like to add, and for simple cases, the program will generate a graph for you. These are good tools.

It gets trickier, though, if the data doesn’t easily fit one of the simple, predefined patterns. The more specific your graph requirements are, the more detailed your instructions to the graphing system in your spreadsheet need to become. There comes a point where the limitations of the tools make them harder to use rather than easier. Now, you not only need a clear idea of how you want your graph to work but also a deep understanding of how to get around, or apply, the programming model that was in the head of the graphing-system developer.

Text is a surprisingly flexible, concise way of encoding ideas.

Fear of Over-Engineering

Many factors push developers to abdicate responsibility for quality. One of them is pressure, real or perceived, to get the job done efficiently. I have heard commercial people worry about software developers and teams “over-engineering.” This is a real fear, and we technical professionals are to blame. We have been guilty of over-engineering sometimes.

Abstraction vs. Pragmatism

I once worked on a project for a client, a big insurance company. This was a “rescue project.” I worked for a consultancy that was pretty well known for being able to go in and deliver effective solutions to projects that were stuck or had failed in previous attempts.

This project had failed fairly spectacularly, twice. It had been in development for more than three years, and they had nothing to show for it that was usable.

We started work and were making decent progress on a replacement. We were approached by an architect from the “strategy group” or some such name. He insisted that our software must comply with the “global architecture.” So I, as the tech lead for the project, looked into what that would entail.

They had a grand plan for a distributed, service-based component architecture that abstracted their entire business. They had services for technical things as well as domain-level, useful behaviors. Their infrastructure would look after security and persistence, as well as allow the systems in the enterprise to be fully integrated with each other.

As by now, I am sure you suspect, this was all vapor-ware. They had lots of documents and a fair amount of code that didn’t work as far as I could see. This project was being built by a team of more than 40 people and was about three or four years late. All projects were mandated to use this infrastructure, but no project ever did!

It sounded like magic because it was magic; it was imaginary.

We politely declined and finished the system that we were building without using the ideas or tech from this architecture.

On paper the architecture looked fine, but in practice, it was only theory.

We are technologists. As a result, we share certain tendencies. One of those tendencies that we should be aware of, and guard against, is chasing “technically shiny ideas.” I am as guilty as anyone of being interested in technical ideas. This is part of the appeal of our discipline, the kind of learning that we value. However, if we are to be engineers, we must adopt a degree of pragmatism, skepticism even. Part of my definition for engineering, at the start of this book, included the phrase “within economic constraints.” We should always be thinking of the simplest route to success, not the coolest, not the one with the most tech that we can add to our CVs or résumés.

By all means, keep up-to-date with new ideas. Be aware of new technologies or approaches to our work, but always evaluate their use honestly in the context of the problem that you are trying to solve. If you are applying this tech, or idea, to learn if it is useful, then recognize that fact and carry out your exploration quickly and efficiently as trial, prototype, or experiment, not as the cornerstone of your new architecture on which the future of the company depends. Be prepared to discard it if it doesn’t work out, and don’t risk the entire development on tech that looks cool.

In my experience, if we take this idea of “striving for simplicity” seriously, we are more, rather than less, likely to end up doing something cool. We are more, rather than less, likely to enhance the value of our CVs and résumés, too.

There is another way in which we are often lured to over-engineer our solutions. That is to make them future-proof . If you have ever said or thought, “We may not need this now, but we probably will in the future,” then you were “future-proofing.” I was as guilty of this as anyone else in the past, but I have come to regard it as a sign of design and engineering immaturity.

We attempt this kind of design future-proofing to give us some insurance that we will be able to cope with future enhancements, or changes in requirements. This is a good aim, but the wrong solution.

Referring to Kent Beck’s Extreme Programming Explained book again, he introduced me to the following concept:

YAGNI : You Ain’t Gonna Need It!

Kent’s advice was that we should write code to solve the problem that faces us right now and only that. I strongly reiterate that advice, but it is part of a larger whole.

As I have already said many times in this book, software is weird stuff. It is almost infinitely flexible and extremely fragile. We can create any construct that we want in software, but we run the risk of damaging that construct when we change it. The problem that people are trying to address when they over-engineer their solutions, by attempting to future-proof them, is that they are nervous of changing their code.

In response to that nervousness, they are trying to fix the design in time now, while they are paying attention to it. Their aim is that they won’t need to revisit it in the future. If you have made it this far through this book, you will know by now that I think that this is a very bad idea, so what could we do instead?

We could approach the design of our code so that we can return to it at any point in the future when we have learned something new and change it. We can take advantage of that nearly infinite flexibility. Now the problem that we need to fix is that of the fragility of our code.

What would it take to give us confidence that we can safely change our code in the future? There are three approaches, and one of them is stupid.

We could be so smart that we completely understand the code and all of its implications and dependencies so that we can safely make changes. This is the hero-programmer model, and although this is the stupid one, this is also one of the more common strategies as far as I can tell.

Most orgs have a usually small number of people “heroes” 4 who are called on to “save the day” when things go wrong or who are called on for the tricky changes that need to be made. If you have a hero in your organization, she needs to be working to spread her knowledge and to work with others to make the system more understandable. This is profoundly more valuable than the more usual firefighting that “heroes” more commonly undertake.

The real solutions to the problem of being afraid to change our code are abstraction and testing . If we abstract our code, we are, by definition, hiding the complexity in one part of the system from another. That means that we can more safely change code in one part of the system, with a much higher level of confidence that our change, even if wrong, will not adversely affect other parts. To be even more sure of this, we also need the testing, but as usual the value of testing is not that simple.

Improving Abstraction Through Testing

In Figure 4.2 , I showed a flattened Cost of Change graph, representing the ideal situation in which we would like to be able to make any change at any time, for roughly the same cost in terms of time and effort.

  1. There is a lovely, fictional example of this in Gene Kim’s book The Phoenix Project , where the character Brent Geller is the only person who can save the day.

To achieve this flat Cost of Change curve, we’d need an effective, efficient strategy for regression testing, which really means a wholly automated strategy for regression testing. Make a change, and run the tests so that you can see where you broke things.

This idea is one of the cornerstones of continuous delivery, the most effective starting point for an engineering approach that I know of. We work so that our software is “always in a releasable state,” and we determine that “releasability” through efficient, effective, automated testing.

However, there is another aspect of testing that is important, beyond merely catching our mistakes, and it is much harder for people to spot if they have never worked this way.

That is the impact of testability on design that I have described previously. We will explore this idea in more depth in Chapter 14 . Specifically, though, in the context of abstraction, if we approach our tests as mini-specifications for the desirable behavior of our code, then we are describing that desirable behavior from the outside-in.

You don’t write specification after you have completed the work; you need them before you start. So we will write our specifications (tests) before we write the code. Since we don’t have the code, our focus is more clearly fixed on making our life easier. Our aim, at this point, is to make it as simple as possible to express the specification (test) as clearly and simply as we can.

Inevitably then, we are, or at least should be, expressing our desires for the behavior that we want, from our code from the perspective of a consumer of it, as clearly and simply as we can. We should not be thinking about the implementation detail that will be required to fulfill that mini-specification at this point.

If we follow this approach, then, by definition, we are abstracting our design. We are defining an interface to our code that makes it easy to express our ideas so that we can write our test case nicely. That means that our code is also easy to use. Writing the specification (test) is an act of design. We are designing how we expect programmers to interact with our code, separate from how the code itself works. All this before we have gotten to the implementation detail of the code. This approach, based on abstraction, helps us separate what the code needs to do from how it does it. At this point, we say little or nothing about how we will implement the behavior; that comes later.

This is a practical, pragmatic, light weight approach to design by contract. 5

Power of Abstraction

As software developers, we are all familiar with the power of abstraction, as consumers. When we become software producers though many developers pay abstraction too little attention in their own code.

Early operating systems didn’t have much in the way of hardware abstraction compared to their modern successors. These days if I want to change the video card in my PC, there are a whole stack of abstractions that insulate my applications from such changes, so I can make that change in the confidence that my apps will most likely continue to work and display things.

  1. Design by contract is an approach to software design focused on the contracts, which are specifications that the system, or components of it, support. See https://en.wikipedia.org/wiki/Design_by_contract .

Modern cloud vendors are busy working on abstracting away much of the operational complexity of running complex, distributed, scalable applications. An API like that of Amazon Web Service’s S3 is deceptively simple. I can submit any sequence of bytes along with a label that I can use to retrieve it and the name of a “bucket” to place it in, and AWS will distribute it to data centers around the world and make it available to anyone who is allowed to access it and provide service-level agreements that will ensure that access in all but the most catastrophic of events is preserved. This is abstracting some fairly complex stuff!

Abstractions can also represent an organizing principle on a broader front. Semantically tagged data structures like HTML, XML, and JSON are extremely popular for communications. Some people say that they prefer them because they are “plain text,” but that is not really true. After all, what does plain text mean for a computer? It’s all electron flows through a transistor in the end, and electrons and transistors are abstractions, too!

The appeal of HTML or JSON for messages sent between different code modules is that the structure of the data is explicit in the communication, and the schema is transmitted along with the content. We could do that with other, much higher-performance mechanisms, like Google’s Protocol Buffers 6 or SBE, 7 but mostly we don’t.

Developers really like the (in practice) horribly inefficient mechanisms like JSON or HTML because everything can work with them. That is because of another important abstraction: plain text. Plain text isn’t plain, and it isn’t text; it is a protocol and an abstraction that allows us to deal with information without worrying too much about how that information is organized other than at some pretty basic level of it being represented as a stream of characters. Nevertheless, it is still an abstraction that is hiding information from us.

This “plain text” ecosystem is pervasive in computing, but it isn’t natural, or inevitable. People designed it, and it has evolved over time. We needed to agree on things like byte ordering and encoding patterns. All of that is before we even begin to think about the underlying abstractions, through which we understand the hardware that our software runs on.

The “plain text” abstraction is an extremely powerful one. Another extremely powerful abstraction is that of “files” in computing, brought to its height in the Unix model of computing in which everything is a file. We can connect logic to build up new, more complex systems, by “piping” files from the output of one module to the input of another. All of this is “made up” and is just a useful way of imagining and organizing what is really going on.

  1. Google’s Protocol Buffers are meant to be a smaller, faster, more efficient version of XML. Read more at https://bit.ly/39QsPZH .

  2. Simple Binary Encoding (SBE) is used in finance. It is a binary data encoding approach that allows you to define data structures and have code generated to translate them at either end. It shares some of the properties of other semantic data encoding approaches, but with lower performance overhead. Read more here: https://bit.ly/3sMr88c .

Abstractions are fundamental to our ability to deal with computers. They are fundamental to our ability to understand and deal with the systems that we create to add value to our computers, too. One way of looking at what it is that we do when we write software (and it is the only thing that we do in some ways) is to create new abstractions. The key is to create good ones.

Leaky Abstractions

Leaky abstractions are defined as “an abstraction that leaks details that it is supposed to abstract away.”

This idea was popularized by Joel Spolsky, who went on to say this:

All non-trivial abstractions are leaky. 8

I have occasionally heard people excuse terrible code by saying something along the lines of “all abstractions are leaky, so why bother?” Well, this completely misses the point of both the original post and of abstraction in general.

Computers and software would not exist without abstraction. The idea of “leaky abstractions” is not an argument against them; rather, it describes that abstractions are complex things that we need to take care over.

There are also different kinds of “leaks.” There are leaks that are impossible to avoid, for which the most effective course is to think about them carefully and work to minimize their impact. For example, if you want to build a low-latency system that processes data at “as close to the limits of the hardware as you can get,” then the abstractions of “garbage collection” and “random access memory" will get in the way because they leak in terms of time, by making the latency a variable. Modern processors are hundreds of times faster than RAM, so access is not random if you care about time. There is a different cost, in time, depending on where the information that you want to process comes from. So you need to optimize to take advantage of the hardware; you need to understand its abstractions, caches, prefetch cycles, and so on, and allow for them in your design, if you want to minimize the impact of the leak.

The other kind of leak is really a point at which the illusion that your abstraction attempts to convey breaks down because you ran out of time, energy, or imagination to cater for that break in your design.

An authorization service that reports functional failures as HTML errors and a business logic module that returns NullPointerExceptions are both breaking business-level abstractions with technical failures. Both of these are a kind of break in the continuity of the illusion that the abstraction is intended to convey.

In general, try to cope with this second kind of leak by trying to maintain a consistent level of abstraction as far as possible. It may be acceptable that a remote component exposed as a web service of some kind reports communications failures via HTML; that is a problem in the technical realm of abstraction of networking and communications, not in the world of the service itself. The mistake is using HTML error codes for business-level failures of the service. This is a break in the abstraction.

  1. You can read Joel Spolsky’s original post here: https://bit.ly/2Y1UxNG .

One take on this is that abstraction, all abstraction, is fundamentally about modeling. Our aim is to create a model of our problem that helps us reason about it and helps us to do work. I like this quote from George Box :

All models are wrong, some models are useful. 9

This is always the situation that we are in. However good our models, they are representations of truth, not the truth itself. Models can be enormously useful even when fundamentally untrue.

Our aim is not to achieve perfection but to achieve useful models that we can use as tools to solve problems.

Picking Appropriate Abstractions

The nature of the abstractions that we choose matters. There is no universal “truth” here; these are models.

A good example of this are maps (the human kind of “map,” not the computer language data structure). All maps are abstractions of the real world, of course, but we have different types of abstraction depending on our needs.

If I want to navigate a boat or a plane to a destination, it is useful to have a map that allows me to measure a course between two points. (This kind of map is, strictly, called a chart , which means that I can measure a “bearing” on a chart, and if I steer that course, I will get to the right place.) The idea of the constant bearing chart was invented by Mercator in 1569.

Without boring you with too much detail, constant-bearing charts are based on things called Rhumb-lines . You can measure a bearing on this kind of map, and if you start off at point A and sail (or fly) that bearing, you will end up at point B.

Now, as we all know, the world isn’t a flat plane. It is a globe, so in reality this is not the shortest distance between A and B because on the surface of a sphere the shortest distance between two points is a curve, and that means that the bearing changes constantly. So the abstraction of a chart hides the more complex math of curved planes and provides a practical tool that we can use to plan our course.

This abstraction leaks in the fact that the distance that you travel is longer than absolutely necessary, but since we are optimizing for ease of use, while planning and sailing, all is good.

  1. A quote from statistician George Box, though the idea is older. See https://bit.ly/2KWUgbY .

A completely different abstraction is used for most underground train maps. This was invented by Harry Beck in 1933.

Harry’s map has become a design classic, and the idea is used all over the world to depict how to get around on an underground train network. Harry realized that when navigating the London Tube (London’s underground system), you don’t care where you are when you are in transit. So he built a topologically accurate map of the network that bore no real relationship to the physical geography.

This style of map, this abstraction, allows passengers to see which trains go to which stations and which stations have connections to other lines extremely clearly. But if you try to use it to walk between the stations, the abstraction breaks down. Some stations are within a few paces of each other but look far apart; others look close but are distant.

My point is that it is fine to have different abstractions—even different abstractions—for the same thing. If we were tasked to thread a network cable between stations on the London Underground, we’d be stupid to choose Harry’s map. But if we wanted to travel from Arsenal Tube Station to Leicester Square for dinner, we’d be stupid to choose a geographical chart.

Abstraction, and the modeling that is at its heart, is a fundamental of design. The more targeted the abstractions are to the problem that you are trying to solve, the better the design. Note, I didn’t say “the more accurate the abstraction.” As Harry’s Tube map so clearly demonstrates, the abstraction doesn’t need to be accurate to be enormously useful.

Yet again, testability can give us early feedback and inspiration in our attempt to come up with useful abstractions.

One of the common arguments against unit testing, and sometimes against TDD, too, is that the tests and the code become “locked together,” and everything becomes more difficult to change. This is much more a criticism of unit testing, where the tests are written after the code is complete. Inevitably, such tests are tightly coupled to the system under test, because they were written as tests rather than as specifications. TDD suffers less from this problem because we write the test (specification) first and are led to abstract the problem, as I have described.

The subtlety here, though, and the enormous value that TDD delivers, is that if I have written my abstract specification, focusing on what the code should do and not how it achieves that outcome, then what my test is expressing is my abstraction. So if the test is fragile in the face of change, then my abstraction is fragile in the face of change. So I need to think harder about better abstractions. I know of no other way of getting this kind of feedback.

The next chapter talks about coupling. Inappropriate coupling is one of the most significant challenges for software development. This entire section of the book is really about the strategies that allow us to manage coupling. The problem is that there is no free lunch. Overly abstract designs can be as big a pain as under-abstracted designs. They can be inefficient and impose unwanted developmental and performance costs. So, there is a sweet spot to hit, and the testability of our system is a tool that we can use to hit it.

In general, our objective should be to retain our ability to change our mind about implementation, and as far as we can our design, without too much extra work. There is no fixed recipe here. This is the real skill of good software development, and it comes with practice and experience. We need to build up our instincts to be able to spot design choices that will limit our ability to change our minds later and that allow us to keep our options open.

What this means is that any advice I offer here is contextual. However, here are a few guidelines, rather than rules.

Abstractions from the Problem Domain

Modeling the problem domain will give your design some guide rails. This will allow you to achieve a natural for the problem domain separation of concerns as well as helping you, maybe even forcing you, to better understand the problem that you are attempting to solve. Techniques like event storming 10 are a great starting point to mapping out the territory of a problem.

Event storming can help you identify clusters of behavior that may represent concepts of interest, and the interesting concepts are good candidates for modules or services in your design. It can highlight bounded contexts and natural lines of abstraction in the problem domain that will tend to be more decoupled from one another than other, more technical divisions.

Domain-Specific Languages

One idea that certainly is more promising in raising the level of abstraction is the idea of the domain-specific language (DSL). However, by definition a DSL is not general purpose. It is, intentionally, more narrowly focused and can be more abstract, hiding detail.

This is the effect that we really see when we see diagram-driven development systems demonstrated. We are seeing the impact of a DSL—in this case a graphical one—on solving narrowly scoped problems. In this space, these more constrained ways to represent ideas are extremely powerful and useful.

DSL is an extremely useful tool and has an important role to play in developing powerful, maybe even “user-programmable” systems, but it is not the same thing as general-purpose computing, so it is not really the topic of this book; therefore, we will leave it there, but as a brief aside, there is no better way to create effective test cases than to create a DSL that allows you to express the desirable behaviors of your system as “executable specifications.”

  1. Event storming is a collaborative analysis technique invented by Alberto Brandolini that allows you to model interactions within a problem domain. See http://bit.ly/3rcGkdt .

Abstract Accidental Complexity

Software runs on computers. The way that computers work presents its own series of abstractions and constraints that we are forced to contend with. Some of these are deep, at the level of information and information theory, like concurrency and sync versus async communications. Others are a bit more hardware-implementation-specific like processor caching architecture, or the difference between RAM and offline storage.

Except for the most trivial of systems, you can’t ignore these things, and depending on the nature of your system, you may have to consider them very deeply. However, these are abstractions that will inevitably leak. If the network is down, your software will be affected, eventually.

In general, in my designs, I aim to abstract the interface between the accidental complexity realm and the essential complexity (problem domain) realm as far as I can. This does take a bit of good design thinking and a bit of thinking like an engineer.

The starting question is, how do I represent the accidental-complexity world in the essential complexity domain? What does the logic of my system need to know about the computer it is running on? We should be striving to make that knowledge minimal.

Listing 12.1 shows the three examples of cohesion from Chapter 10 . If we look at these from the perspective of abstraction and the separation of accidental and essential complexity, we can gain more insight.

Listing 12.1 Three Cohesion Examples (Again)

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)

The first example, add_to_cart1 , doesn’t abstract at all and is a bit of a mess as a result.

The next, add_to_cart2 , is better. We have added an abstraction for storing information. We have created a “seam” in our code called store , and this allows the code to be more cohesive, drawing a clean line in the separation of concerns between the essential functions of our domain, adding items to carts, and calculating totals and the accidental complexity caused by the fact that our computer makes a distinction between volatile but quick RAM and slower but nonvolatile disk.

Finally, in add_to_cart3 , we have an abstraction that leaves our essential complexity code uncompromised. Our abstraction is intact, with the very slight concession of the introduction of the idea of something that is interested in what happened, a Listener .

In terms of the consistency of the abstraction, add_to_cart3 is, to my mind, the best. Even the concept of storage has been removed.

The beauty of this abstraction is how clean the model is of accidental concerns and, as a result, how easy it would be to test it or to enhance this code with new behavior on_item_added .

The cost to this abstraction, the leak that may get in the way of add_to_cart3 being the best choice, raises the question, what happens if the attempt to store fails? What happens if our database runs out of connections in the connection pool or our disk runs out of space or the network cable between our code and the database is dug up by accident?

The first example is not modular, it lacks cohesion, it conflates accidental and essential complexity, and there is no separation of concerns; this is still just bad code!

The other two are better, not for any artificial notion of beauty or elegance but for practical, pragmatic reasons.

Versions 2 and 3 are more flexible, less coupled, more modular, and more cohesive because of the separation of concerns and because of the abstractions that we have chosen. The choice of abstraction between these two is really a design choice that should be driven by the context in which this code exists.

We could imagine several ways that this could work.

If, for example, the lack of storage is transactional with the addition of the item to the cart, then we’d need to undo the change to the cart. This is unpleasant, because the technicalities of the storage are intruding into our previously pure abstraction. Perhaps we could work to limit the extent of the leak; take a look at Listing 12.2.

Listing 12.2 Reducing the Abstraction Leak

Click here to view code image

def add_to_cart2(self, item):
    if (self.store.store_item(item))
        self.cart.add(item) 
    return self.calculate_cart_total();

In Listing 12.2, we stepped back from our fully abstracted version 3 and allowed the concept of “storage” to exist in our abstraction. We have represented the transactional nature of the relationship between storing and adding the item to the cart with a success or failure return value. Note we aren’t confusing our abstraction by returning implementation-specific error codes and leaking those into our domain-level abstraction. We have limited the technical nature of the failure to a Boolean return value. This means that the problems of capturing and reporting the errors are dealt with somewhere else, inside our implementation of “storage” in this case perhaps.

This is a further example of us trying to minimize the impact of the inevitable leaks in our abstraction. We are modeling the failure cases and abstracting them, too. Now we can once again imagine all kinds of implementation of “store.” Our code is more flexible as a result.

Alternatively, we could take a more relaxed, decoupled view. In add_to_cart3 in Listing 12.1, we could imagine that behind the event on_item_added there are some “guarantees.” 11 Let’s imagine that if, for some reason on_item_added fails, it will be retried until it works. (In reality we’d want to be smarter than that, but for the sake of keeping my example simple, let’s stick to that!)

Now we are sure that, at some point in the future, the “store” or anything else that is responding to on_item_added will be updated.

This certainly adds complexity to the communication underneath on_item_added , but it more strongly preserves our abstraction and, depending on context, may be worth the extra complexity.

My objective with these examples is not to exhaustively explore all the options but rather to demonstrate some of the engineering trade-offs that we may choose to make, depending on the context of our system.

The “thinking like an engineer” that I alluded to, and ideally demonstrated here, is in thinking about the ways in which things can go wrong. You may recall that Margaret Hamilton described this as a cornerstone of her approach when she invented the term software engineering .

In this example, we imagined what would happen if the storage failed. We found that in that situation our abstraction leaked. So we were forced to think a bit more and thought of a couple of different ways that we could cope with that leak.

Isolate Third-Party Systems and Code

The other clear difference between version 1 of add_to_store and versions 2 and 3 is that version 1 exposes and couples our code to specific third-party code, in this case sqlite3 . This is a common library in the Python world, but even so, our code is now concretely tied to this specific third-party library. Yet another reason for this code being the worst of the three is because of this coupling to this third-party code.

  1. Computer scientists will, quite correctly, tell you that it is impossible to offer “guaranteed delivery.” What they mean is that you can’t guarantee “exactly once delivery,” but we can work with that. See https://bit.ly/3ckjiwL .

The tiny, insubstantial cost of cutting out the block of code that talks about sqlite3 , connections, and insert clauses, and moving it to somewhere else, away from my code that doesn’t care about any of that stuff, is a big step forward toward greater generality. It’s a big gain for so little work.

As soon as we allow third-party code into our code, we are coupled to it. In general, my preference and advice is to always insulate your code from third-party code with your own abstractions.

Some caveats before we proceed with this idea. Obviously, your programming language and its common supporting libraries are “third-party code,” too. I am not suggesting that you write your own wrapper for Strings or Lists , so as usual my advice is a guideline rather than a hard-and-fast rule. However, I advise that you think carefully about what you allow “inside” your code. My default position is that I will allow language concepts and libraries that are standard, but not any third-party libraries that don’t come with my language.

Any third-party libraries that I use will be accessed through my own facade or adapter that will abstract, and so simplify, my interface to it and provide a usually pretty simple layer of insulation between my code and the code in the library. For this reason I tend to be wary of all-encompassing frameworks that try to impose their programming model on me.

This may sound a little extreme, and it may be extreme, but this approach means that as a result my systems are more composable and more flexible.

Even in the trivial example we have been looking at here, add_to_cart2 presents an abstraction that makes sense in the context of my implementation of storage. I can provide a version that is in essence the block of code implementing storage in sqlite3 from add_to_store1 , but I can also write a completely different kind of store, without needing to modify the add_to_cart2 implementation in any way. I could use the same code in different scenarios, and I could even write some kind of composite version of store that stored my items in multiple places if the need arose.

Finally, we can test our code to this abstraction, which will always be a simpler version than the real thing. As a result, my solution will be dramatically more flexible, and easier to change if I make a mistake, for very little extra work.

Always Prefer to Hide Information

Another strong guideline to help us steer our code in a direction that will keep the doors to future-change open, without breaking YAGNI, is to prefer the more general representations rather than more specific, but this is slightly overly simplistic advice. The clearest demonstration of this idea is probably through functions and method signatures.

Listing 12.3 shows three versions of a function signature. One of these looks a lot better to me than the others, though as usual, it is contextual.

Listing 12.3 Prefer to Hide Information

Click here to view code image

public ArrayList<String> doSomething1(HashMap<String, String> map);
public List<Sting> doSomething2(Map<String, String> map);
public Object doSomething3(Object map);

The first is overly specific. When I collect the return value, do I really ever care that it is an ArrayList rather than any other kind of List? I suppose that I can imagine vanishingly rare cases when I care, but in general I’d prefer not to care. The stuff I am almost certainly interested in is the List-yness, not the ArrayList-yness!

“OK,” I hear you cry. “So always prefer the most abstract, most generic, representation.” Well, yes, but within sensible bounds that maintain your abstraction. I would be dumb to follow this advice and create the rather unpleasant function signature of version doSomething3 . This is generic to the point of being probably unhelpful. Again, there may be times when Object is the correct level of abstraction, but those are, or should be, rare and always in the realm of accidental, rather than essential, complexity.

So, in general, doSomething2 is probably my most common target. I am abstract enough that I am not too tied to the technical specificity of doSomething1 , yet I am also specific enough to be helpful in presenting and maintaining some pointers about how to consume the information that I produce and my expectations for the information that I consume.

I am sure that you will be tired of me repeating this by now, but once again, our ability to identify a sweet spot for our abstractions is enhanced by designing for testability . Attempting to write a test and simulating the use of the interface that we are creating gives us an opportunity to experience and exercise our understanding of that interface to the code under test.

This, in combination with our preference to hide information in general and to prefer the more generic representations of the information that we deal with that make sense in our context will, once again, help us keep the doors to future change open.

Summary

Abstraction is at the heart of software development. It is a vital skill to develop for the aspiring software engineer. Most of my examples are probably rather object oriented, which is because that is how I tend to think about code. However, this is just as true of functional programmer or even assembler programming. Our code, whatever its nature, is better when we construct seams in it that hide information.