Understanding Complexity: Problem and Solution Space
In the previous chapter, we went through the history of DDD and what it tries to solve. We also started to talk about the need to explore the domain, improve our knowledge of it, and find solutions in an iterative way. In this chapter, we will delve into problem and solution spaces, and by the end of it, you will have a clear understanding of their importance not only when approaching a greenfield project but also when refactoring one that already exists. Such a project may already be drifting away with useless features or complexity that do not represent the business anymore. You have probably seen many such types of projects that try to solve problems they themselves create, rather than adding value for the user.
We will explore the intricate nature of modern complex systems and how to navigate their inherent complexity. Understanding these concepts is a fundamental skill for DDD as it allows us to deconstruct and manage the various components that define your system.
Specifically, we’ll cover the following main topics in this chapter:
- Dealing with complexity
- Problem and solution space
- Decision-making and biases
Dealing with complexity
One of the best things about the nineties was that you could deploy new versions of systems with ease. When you were ready, you simply took down the application, upgraded it, and then put it back online. The same was true for our awesome SQL scripts that updated the DB in one fell swoop and, until the end of the nineties, most systems were deployed this way.
These days, you can no longer afford to do this anymore because you do not have the luxury of being able to take down all the components of a system and upgrade them all at once. You must take into account that different teams are working on different components at different speeds, and there could be a lot of DBs that need to be kept somewhat aligned. What we are trying to say here is that the main reason this is not an acceptable way of doing things anymore is because at the root of everything lies complexity. Modern systems are so big and complicated that complexity itself is an inherent characteristic. No matter what you are dealing with, complexity arises from various sources—such as the sheer number of components, their interdependencies, and the dynamic nature of their interactions.
Understanding complexity involves recognizing its multifaceted nature and can be classified into two main types: essential complexity and accidental complexity. Essential complexity is intrinsic to the problem domain and cannot be removed. It is the complexity that arises from the nature of the problem itself. For example, the complexity of a financial trading system is inherent due to the numerous rules, regulations, and market conditions it must adhere to.
Accidental complexity, on the other hand, stems from the solution domain. It is the unnecessary complexity introduced by poor design decisions, inefficient processes, or inadequate tools. Reducing accidental complexity is mandatory for managing and simplifying systems.
Figure 2 .1 is a summary of the key points to classify complexity.
Figure 2 .1 – Key points when dealing with complexity
As we can see in Figure 2 .1 , there is a lot to take into consideration when dealing with complexity, but do not worry; we have tools created by very smart people that can help us tackle it.
One of the first tools we would like to introduce to you is the Cynefin framework ( https://en.wikipedia.org/wiki/Cynefin_framework ).
Cynefin framework
The Cynefin framework was developed by Dave Snowden in 1999, and its name, pronounced /kəˈnɛvɪn/ kuh-NEV-in, is a Welsh word that means “habitat.” We can sum it up by saying that it is a sense-making device that helps individuals and organizations understand and navigate complexity. Figure 2 .2 shows the Cynefin template.
Figure 2 .2 – Cynefin framework, taken from Wikipedia
As we can see in Figure 2 .2 , the framework categorizes situations into five distinct contexts.
Clear context
Clear context represents the “known knowns.” This means that the relationship between cause and effect requires analysis or expertise but is still predictable. Best practices or well-defined rules are already in place. In this situation, the advice is to “sense–categorize–respond”: first, establish the facts (“sense”), then categorize them, and finally, respond by following the rules or applying the best practices. Here, the DDD strategic patterns are useless because we already have a clear vision of the domain and so we can move directly to implementing tactical patterns.
Complicated context
Complicated context represents the “known unknowns”—situations where the relationship between cause and effect requires analysis or expertise but it is still predictable. Good practice and expert advice are applicable. As we can see in Figure 2 .2 , the framework suggests “sense–analyze–respond”: assess the facts, analyze, and apply the appropriate good operating practice. In this specific domain, strategic and tactical patterns are essential to increase its understanding and start moving to a clear context.
Complex context
Complex context represents the “unknown unknowns.” As it were, it is when cause and effect are deducible only in retrospect, there are no right answers, and patterns emerge through interaction. Emergent practices are needed here. “Probe–sense–respond” takes place: small-scale experiments (“probe”) to explore the space and generate data, sense the results, and respond with actions. Strategic patterns with explorative tools come to the rescue to help us root a better vision and comprehension of this context. Tactical patterns are useless here.
Chaotic context
In a chaotic context situation, cause and effect are unclear because there is no clear relationship, and immediate action is required to stabilize the situation. We must “act–sense–respond”: act to establish order, sense where stability lies, and respond to try to turn a chaotic context into a complex context. Novel practices emerge. In this specific context, the pattern of DDD does not help, but we should use other exploration tools to give us a starting point on which we could start to apply strategic patterns.
Confusion context
The confusion context is in the center of Figure 2 .2 and represents situations where there is no clarity about which of the other contexts apply. As written by Snowden and Boone in their article A Leader’s Framework for Decision Making ( https://strategicleadership.com.au/wp-content/uploads/2017/06/A-Leader%E2%80%99s-Framework-for-Decision-Making-HBR-Nov-2007.pdf ): “ Here, multiple perspectives jostle for prominence, factional leaders argue with one another, and cacophony rules .”
Table 2.1 summarizes when we should use strategic, tactical, and explorative patterns.
Strategic patterns | Tactical patterns | Explorative patterns | |
Clear | No | Yes | No |
Complicated | Yes | Yes | No |
Complex | Yes | No | Yes |
Chaotic | No | No | Yes |
Confusion | No | No | Yes |
Table 2.1 – A recap of when we should use strategic, tactical, and explorative patterns
To conclude with a practical example, let us look at the one given by the author himself in 2007. It refers to an incident that happened in 1993 at the Brown’s Chicken and Pasta restaurant in Palatine, Illinois. A shooter murdered seven employees, and as a result, Deputy Police Chief Walt Gasior had to deal with a situation in which the local police faced all the domains. He had to act immediately to manage the initial panic (chaotic), keep the department running by following standard procedures (simple), ask for expert help (complicated), and keep the community calm in the following weeks (complex).
Residuality theory
Another powerful tool we have in our toolbox is residuality theory ( https://www.sciencedirect.com/science/article/pii/S1877050921007420 ). Formulated by Barry O’Reilly, it states that the future of a system is determined by its residues, which are the remnants left behind after the system has been affected by a stressor.
Residuality theory is a pivotal concept in the realm of DDD, offering a structured approach to understanding and improving complex systems. At its core, residuality theory examines how a system retains its structure and behavior after being subjected to changes or disruptions, referred to as stressors.
Imagine a legacy e-commerce platform that struggles to handle peak shopping seasons, such as Christmas or Black Friday. Each peak period acts as a stressor, revealing underlying issues such as slow performance or system crashes. By applying the residuality theory, we analyze these stress responses to identify persistent problems and areas resistant to change.
This method allows us to target refactoring efforts more effectively, ensuring that improvements address the root causes of system fragility. By refactoring this aspect, we enhance the system’s robustness, making it more resilient to future stressors. With this approach, we can better pinpoint which area of our system needs refactoring and design a system that gracefully adapts to evolving demands and challenges.
O’Reilly’s residuality theory presents a nuanced understanding of how systems evolve and sustain themselves through the continuous accumulation of past states and interactions. This theory wants to shift our perspective on change, suggesting that systems (what he calls naïve architectures) do not simply go through isolated, linear steps but are profoundly shaped by the “residue” that remains when facing changes. These residues are active, influential components that affect how systems adapt, resist, and evolve over time.
To truly understand a system, one must consider these residuals, which manifest in various forms, such as legacy code in software, ingrained processes in organizations, or established cultural norms within communities. Each of these residues carries with it the weight of past decisions, interactions, and contexts, creating a complex web that influences current and future states. For example, in the realm of software development, understanding the intricacies of legacy code is essential for making informed decisions about future development and integrations.
Residuality theory advocates for a holistic approach to change management and system design. It encourages us to look beyond immediate actions and outcomes and to consider the deeper, more persistent influences that shape a system’s behavior. By doing so, we can better predict potential challenges, identify areas of resistance, and develop strategies that are more aligned with the underlying reality of the system. This approach contrasts sharply with traditional models of change that often overlook the importance of historical context and residual effects, leading to strategies that may be effective in the short term but fail to sustain over time.
In practical terms, applying residuality theory means engaging in a continuous process of reflection and analysis, where past experiences are not just acknowledged but are critically examined to understand their ongoing impact. This involves not only identifying the residues but also interpreting their significance and leveraging this understanding to inform future actions. For instance, in a business context, leaders might analyze past project failures and successes to identify persistent patterns that could influence current initiatives. In software development, teams might conduct thorough code reviews to understand how past coding practices and design decisions affect current performance and scalability.
Stressors and refactoring
A stressor , in the context of refactoring, is any external factor or event that places pressure on the system and tests its stability, performance, and resilience. As per the example before, this pressure can be caused by a spike in the number of users, unexpected behaviors, and network or hardware failures. These are practical tests that reveal the system’s weaknesses and bottlenecks. Do not equate this with Netflix’s Chaos Monkey though. You identify stressors with brainstorming sessions, analysis of the production system in its ecosystem, or by using random simulation.
Observing and analyzing how your system behaves under these stress scenarios allows you to gain critical insights into system weaknesses and bottlenecks. This understanding is crucial for effective refactoring, enhancing the system’s ability to handle future stressors, and improving overall robustness and reliability.
If you want to learn more on the topic, we suggest watching the speech O’Reilly gave at NDC Oslo in 2023 on YouTube ( https://www.youtube.com/watch?v=0wcUG2EV-7E ).
EventStorming
Last but not least, we want to bring your attention to EventStorming ( https://www.eventstorming.com/ ), a tool created by Alberto Brandolini. This tool is especially useful for the exploration of your domain and is different from other similar tools (i.e., domain storytelling). The idea behind it is quite simple; since your goal is to understand the complexity of the domain, bring all the interested parties, from domain experts to stakeholders, to the table and build a domain model together that is understandable to everyone. There is no single format for EventStorming; it is more of a family of workshops aimed at graphically representing the complexity of key information flows within organizations using events as an exploration tool. There are three main kinds of formats we can choose from, and every single one is specifically designed for different moments of exploration. Let’s go through them in the next sub-sections.
Big picture
When you must deal with the refactoring of a code base, you need to understand what this solution solves, and you need to talk to all the stakeholders of the project, all the businesspeople, and all the developers. The goal is to build a model that represents the flow of all data in your domain. Everything starts by hanging a sheet of paper on the wall, typically 10-15 meters in length (but it usually grows a lot more), and applying fundamental ingredients on it—orange sticky notes. These notes represent events that occur in the domain, and, usually, after a couple of hours of discussions and writing of orange stickies, you will see that processes start to emerge on the wall as a flow represented by all the orange sticky notes. From here, you will be able to start exploring with the stakeholders the different ways in which they perceive the same problem.
In this phase, it is important to understand whether these ways are simply different in solving the problem or whether each stakeholder has a different point of view on it. You will end up with a defined common language between developers, business experts, and stakeholders. Figure 2 .3 shows an example of events in an EventStorming session with added notes about topics that must be covered during the detailed analysis of the flow. The scope of the big picture is to highlight the main events and potential pain points throughout the business flow.
Figure 2 .3 – EventStorming big picture result
Process modeling
In this case, the scope of the exploration is more limited, and so is the team dimension. You need to create a space in which each stakeholder can contribute to creating the model, and for this reason, you cannot use tools such as UML, otherwise, only developers could participate, or Business Process Modeling Notation, because only businesspeople could participate. You need to enable conversations between all the members of the domain so that you can create a model to share between them.
In Figure 2 .4 , you can see all the types of sticky notes that you can use during an EventStorming session. Having a common model avoids misinterpretation, and with that, you don’t lose any details on the business flow.
Figure 2 .4 – The grammar of EventStorming process modeling
To achieve this goal, you have to add more types of sticky notes to EventStorming’s grammar. You do not need a design of the processes as a result of your exploration, but to encourage the conversation, so that you can use a tool as simple as possible to be understood by everyone. For example, during refactoring, it is very important to identify the right boundaries to split our monolith with. That separation represents the way in which you will extrapolate the microservices architecture.
Software design
With the previous workshop, you end up with a clear definition of the domain boundaries. Now, with this third format, you are going to explore in detail every single one of them, so that the grammar will be richer.
Figure 2 .5 – All of the elements used during EventStorming
With this workshop, you will identify the aggregate of your bounded context , as well as the domain events , commands , services (internal and external), policy , and all the objects you need to design your solution. The aim of this workshop is to provide a detailed structure of the software for the team using the language that you discovered during the previous EventStorming sessions, and the details of all objects discovered in this one.
Now that you have understood the importance of knowledge, you can discover how deep you can go into the problem and try to solve it.
Problem and solution space
Among the many phrases apocryphally attributed ( https://quoteinvestigator.com/2014/05/22/solve/ ) to Albert Einstein, there is one that goes as follows:
“If I had an hour to save the world, I would spend 55 minutes defining the problem and only 5 minutes finding the solutions.”
We could summarize this statement by saying that the problem space is the set of all the problems that your application should solve, while the solution space is the set of all solutions that address each given problem.
Allen Newell and Herbert Simon in their book Human Problem Solving argue that we, as human beings, tend to be problem solvers. We see this daily in our team while developing software. We tend to seek and try to find a solution as quickly as possible and leave the problem space as quickly too. We are uncomfortable staying in this area, but it is where our client needs to reside; it is the zone that allows us to acquire more information about the problems our client asks us to solve through the software we will develop for them because writing software means solving business problems! Essentially, this space constitutes the foundation upon which the solution space will rest. Mathematically speaking, the problem space is always a subset of the solution space. Therefore, we should not rush to leave the former to move, with poor domain knowledge, to the latter. As developers, to demonstrate our capabilities, we tend to provide a solution as soon as possible, as if to show that we are good at our job by providing solutions fast to our clients.
By acting this way, however, we do not delve deeply enough into the problem; we are taking a shortcut to exit an uncomfortable zone. If we are then given requirements, our biases suggest the solution to propose! Unfortunately, such a solution will always be incomplete, at best, and wrong, at worst, because it is at this stage that projects begin to fail. We will realize it later when it is already too late, but the root of the failure lies in not having thoroughly investigated the problem space.
Staying in the problem space means resisting the urge to prematurely jump into solutions. It requires a disciplined approach to fully understand and articulate the problem before considering any solution. This involves engaging with stakeholders to capture their perspectives, conducting thorough research, and employing techniques such as domain modeling and scenario analysis to explore all facets of the problem.
By deeply investigating the problem space, we uncover the underlying causes, constraints, and nuances that might not be immediately obvious. This process often reveals critical insights that significantly influence the design and implementation of the solution. It ensures that the problem is framed correctly, which is essential for creating effective and sustainable solutions.
Furthermore, staying in the problem space helps to mitigate biases and assumptions that can cloud judgment. It promotes a culture of curiosity and continuous learning within the team, where questions are encouraged, and diverse viewpoints are valued. This collaborative exploration fosters a shared understanding of the problem, aligning all stakeholders around a common goal.
Neglecting this phase leads to superficial solutions that fail to address the core issues. Projects that skip through problem investigation often suffer from scope creep, missed requirements, and ultimately, failure to deliver value. In contrast, a robust exploration of the problem space lays a solid foundation for successful projects, ensuring that solutions are not only technically sound but also relevant and impactful.
Figure 2 .6 summarizes the differences between them.
Figure 2 .6 – Problem space versus solution space
The urge to provide an adequate solution soon from the start means starting off on the wrong foot. We all know that our applications start small but are destined to grow over time, some very quickly: as customer demands grow, a small deviation at the beginning of the journey will lead us to a destination different from what was imagined, making it increasingly difficult to align our solution with the actual problem solution.
How can we avoid all of this? By staying in the problem space as long as possible, just like in Einstein’s quote. Even Evans proposes an exploratory model, consisting of continuous iterations of analysis, proposal, and feedback, as shown in Figure 2 .7 .
Figure 2 .7 – Model exploration whirlpool
Evans defines the action of finding a solution from the beginning to the entire problem as what we colloquially call big front design: a block “locking in our ignorance.” The problem with this type of approach is that we are forced to make a lot of important decisions about our solution when we have less knowledge of the problem itself.
To counter this, Dan North suggests extreme caution in moving toward a definitive solution. In his article Introducing Deliberate Discovery ( https://dannorth.net/introducing-deliberate-discovery/ ), he advocates for a proactive exploration of the domain knowledge, emphasizing the importance of identifying and understanding what we do not yet know about the domain. Let’s spend some time going through the important parts of the article.
Deliberate discovery
The main terms covered in North’s article are as follows:
- Deliberate discovery : Emphasizes the importance of actively seeking knowledge to reduce ignorance in projects.
- Learning versus ignorance : Identifies ignorance as a primary constraint to project success and highlights the need for proactive learning
- Accidental versus deliberate learning : Contrasts passive, accidental learning with intentional, deliberate discovery to accelerate knowledge acquisition
- Non-linear discovery : Discusses how learning happens in irregular, often unexpected ways
- Assumption of problems : Advocates planning with the expectation that unpredictable problems will arise, thus preparing better responses
The key recommendations made by North are as follows:
- Focus planning on knowledge acquisition rather than merely estimating the task
- Recognize and address various forms of ignorance (technical, domain-specific, organizational)
- Make deliberate efforts in discovery to significantly improve project outcomes by reducing unknowns early
- Acknowledge that learning happens in spurts, often influenced by unforeseen challenges
- Prepare for bad events proactively to mitigate their impact on projects
Now let us look at another perspective that delves into the risks of big front design stemming from lack of awareness. Interestingly, “lack of awareness” is termed as the “2 nd order of ignorance” in Phillip G. Armour’s article titled The Five Orders of Ignorance ( https://cacm.acm.org/opinion/the-five-orders-of-ignorance/ )
.Five orders of ignorance
The main argument in Armour’s article is that the true product of software development is the knowledge embedded in the software; creating functional software requires understanding what “works.”
If knowledge is the key, then the following is also true:
- Building effective software is primarily about acquiring the necessary knowledge
- Software development should be viewed as a knowledge-acquisition process rather than a product-production activity
Starting with these considerations, we end up with five orders of ignorance :
- 0th order ignorance (0OI) : Lack of ignorance – you know something and can demonstrate it
- 1st order ignorance (1OI) : Lack of knowledge – you don’t know something, but you know what you don’t know
- 2nd order ignorance (2OI) : Lack of awareness – you don’t know you don’t know
- 3rd order ignorance (3OI) : Lack of process – you don’t know a suitable process to find out what you don’t know
- 4th order ignorance (4OI) : Meta ignorance – you don’t know about the five orders of ignorance
If ignorance is the opposite of knowledge, how can we remain in the problem space to bridge 1OI and increase awareness of 2OI? How do we control our tendency to propose solutions too quickly?
Bridging gaps in ignorance
To address the challenge of navigating between known and unknown gaps in knowledge, we recommend the following useful tips:
- Maintain control of the discussion : You don’t have to talk continuously, but you have to avoid the discussion converging too quickly to a conclusion. Often, a signal to a colleague is enough to change the focus of the conversation with the client. The main reason for maintaining control of the discussion is that clients—or their representatives—often assume certain information is understood and leave it unsaid, so it’s up to us to surface and clarify those assumptions.
- Listen to different solutions : In initial meetings with a client, participants are often hesitant to speak or propose ideas. Then, after the ice is broken thanks to our capable agile coach, solutions start to emerge and sometimes conflict with each other. It is important to maintain a healthy and positive environment by including everyone’s suggestions in the solution space.
- Keep the main solution hidden : As the moderator of the problem exploration, your task is to keep the solutions that globally prove to be valid hidden for as long as possible. For example, if you use EventStorming as an exploration tool, let participants continue to attach sticky notes to the wall, and perhaps guide them in a direction so that the main solution emerges autonomously. Highlight solutions that seem similar and focus attention on them to understand whether they are different expressions of the same solution or totally different ones.
Staying in the problem space is certainly uncomfortable for both parties: the client and the supplier. The former feels a bit under pressure due to the countless questions they keep receiving, and the latter, often us, can’t wait to propose a solution. Completely addressing the client’s problem takes time, and it’s not always convenient to insist on deeper investigation or prolonged questioning during the first meeting. The important thing is to identify the boundaries of the problem and start proposing a solution that can be revisited for feedback and continued after potentially adjusting the course.
Our domain will always be in constant evolution, if only for everything that belongs to the level of unknown unknowns – the things we still don’t know we don’t know but will discover as we become greater experts in the domain we are working on. At this point, we need to understand how to approach such a solution, from an architectural point of view. And for this, we need to explore the domain before creating a model.
Deleuzian walk
We have already seen how the abstractions of reality can be dangerous to solve a problem. Creating a good model is the primary goal, either during the first design of your solution or while you are working to refactor it. But how do we do this? EventStorming, like storytelling and other tools, is good for exploring the domain together with all team members before creating a model. However, an alternative way to run an exploration is to simply experience the domain itself, just as we explore the territory around us when we walk.
This form of exploration is known as the Deleuzian walk and describes an alternative way of learning. The term comes from the ideas of Gilles Deleuze, as described in his 1968 book Difference and Repetition , which can be summarized as follows:
- Philosophy of difference : Deleuze challenges traditional philosophy’s focus on identity and sameness, advocating for a deeper exploration of differences
- Repetition and novelty : He explores how repetition can generate new meanings or variations, challenging the idea that repetition simply reinforces what already exists or remains the same.
- Ontology : Deleuze presents being as inherently different, emphasizing uniqueness over uniformity
- Time and memory : The roles of time and memory are scrutinized for their impact on cultivating differences
- Conceptual tools : Deleuze navigates through his arguments employing complex philosophical constructs such as the virtual, the actual, and intensity
When you walk along a new path for the first time, you are totally involved in looking at the map to be sure to get back home safely. After a few times, you start to discover new things on your journey because now you know the path, and you can pay attention to the environment around you, the mountains around the valley, or the river at the bottom. You will see new landscapes or discover new alternative ways of traveling in the same space. When you bring your friends with you, they will see different things, because their interests are different from yours. Instead of understanding the world around you, you are contemplating it, and you become very rich. You are changing your way of thinking, from learning from the map (linear), in which the map provides an objective, well-defined, description of the walk, to observing the world around you with your eyes and discovering new things (laterally).
This metaphor is quite fitting for domain exploration. As the environment changes during the different seasons, your domain also changes due to new business requirements, or simply because the world changes constantly and so does the business flow. This means that our structure is constantly changing, and implementing certain structures too early could be very dangerous and unproductive.
During domain exploration, knowledge is much preferable in contrast to the developer’s need for an immediate concrete implementation. So, Deleuze’s ideas map perfectly with the model exploration whirlpool shown in Figure 2 .7 . Basically, it is important to discover your domain iteratively and increase your knowledge of the domain step by step. Remember that you are a developer and do not necessarily know from the start the domain you will work on.
Decision-making and biases
By now, it should be clear why it is important to spend most of our time understanding the problem instead of finding a solution, and now we can delve into the last aspect of handling complexity. This includes cognitive aspects of decision-making and how biases can impact the process, especially in the context of refactoring complex systems using DDD patterns and principles. Understanding these cognitive processes will help you make more informed and rational decisions during your refactoring journey.
Understanding System 1 and System 2
Daniel Kahneman, a renowned psychologist and Nobel laureate, introduced the concept of two systems of thinking in his book Thinking, Fast and Slow . These systems are fundamental to understanding human decision-making processes and are called System 1 and System 2 .
System 1 is efficient for routine tasks and familiar situations but can be prone to biases and errors when dealing with complex or unfamiliar problems. System 2, on the other hand, is slower and more deliberate and allows us to make more rational and informed decisions, especially when dealing with unfamiliar or complex situations. Their key traits are as follows:
-
System 1 – fast and intuitive : System 1 operates automatically and quickly, with little or no effort and no sense of voluntary control. It is our intuitive system, which we use for quick judgments and decisions. Examples of System 1 thinking include the following:
- Recognizing a familiar face in a crowd
- Answering simple arithmetic questions (e.g., 2 + 2 = 4)
- Driving a car on an empty road
-
System 2 – slow and deliberate : System 2 allocates attention to the effortful mental activities that demand it, including complex computations. It is our analytical system, which we use for critical thinking and complex problem-solving. Examples of System 2 thinking include the following:
- Solving a complex mathematical problem
- Making a strategic decision in a business context
- Refactoring a complex software system
The importance of Systems 1 and 2 in refactoring
Refactoring, particularly in complex systems, requires a balance between intuitive and deliberate thinking. Here’s how understanding and applying System 1 and System 2 can enhance your refactoring efforts.
To leverage both systems, you must understand when and how to use them during the refactoring process. Starting with System 1, an experienced developer can quickly recognize patterns, code smells, and where to start a refactoring process through past experiences. Also, for minor tasks, such as extracting small methods, System 1 can be effective. System 2 kicks in when you deal with large-scale refactoring, such as restructuring an entire module or re-architecting a system. Here, deliberate thinking is crucial. It also helps in creating a refactoring plan and identifying potential risks ahead. As a last important thing, System 2 can help mitigate biases that could emerge with System 1.
Common cognitive biases in refactoring
Refactoring is as much a mental process as a technical one, and our cognitive biases can significantly impact the outcomes. Recognizing these biases and taking steps to counteract them can help you avoid potential pitfalls. Let’s look at the main ones and what you can consider doing to mitigate them.
Anchoring bias
Anchoring bias occurs when we rely too heavily on the first piece of information encountered (the “anchor”) when making decisions. As stated, this might mean sticking to the first solution or design without considering other alternatives. You should encourage team discussions and explore multiple solutions before settling on a decision.
Here’s how to counteract it:
- Encourage exploration : Actively brainstorm multiple solutions before committing to one. Use tools such as design spikes or proof-of-concept development to evaluate alternatives.
- Adopt decision frameworks : Use structured techniques such as decision matrices to evaluate options objectively.
- Set a “cooling-off period” : Give the team time to reflect on initial ideas before making a final decision.
Confirmation bias
Confirmation bias is the tendency to search for and remember information that confirms one’s preconceptions. This can lead to ignoring critical feedback or alternative approaches during refactoring. To mitigate this bias, you can seek different opinions and rely on thorough code reviews to challenge your decisions.
Here’s how to counteract it:
- Foster a culture of challenge : Encourage team members to play devil’s advocate during discussions. Assign someone to question the prevailing assumptions in every meeting.
- Emphasize diverse perspectives : Actively involve people from different roles or with varying expertise to review designs and refactoring plans.
- Automate feedback : Use tools such as static code analyzers and automated tests to surface objective insights, reducing reliance on subjective interpretations.
Availability heuristic
The availability heuristic involves prioritizing events based on vividness or recency instead of their frequency, such as a plane crash versus a car crash. The latter is more frequent, but we tend to think of the former more often. This can result in overestimating the importance of recent events that are n ot the norm and potentially lead us to suboptimal refactoring decisions. We should force ourselves to base our decisions on objective data rather than recent experiences alone.
Here’s how to counteract it:
- Rely on historical data : Analyze metrics such as defect rates, code churn, or feature usage to guide refactoring priorities
- Maintain a refactoring log : Document past refactoring efforts, lessons learned, and their outcomes to ground future decisions in accumulated knowledge
- Encourage structured retrospectives : Reflect regularly on past decisions to identify patterns that can inform better judgment
Practical example – refactoring a legacy system
Let’s consider a practical example to illustrate the application of System 1 and System 2 thinking in refactoring a complex system. Imagine you are tasked with refactoring a monolithic application into a more modular and maintainable structure using DDD principles. This scenario provides an excellent opportunity to demonstrate how both types of thinking can be leveraged throughout the refactoring process.
Your approach would likely begin with an initial assessment, combining both System 1 and System 2 thinking. You’d use your intuitive System 1 to quickly identify obvious code smells and areas that need improvement. Simultaneously, you’d engage your analytical System 2 thinking to perform a detailed analysis of the system’s architecture, dependencies, and business domains. This deeper, more deliberate analysis provides a comprehensive understanding of the system’s complexity.
With a clear picture of the system, you move on to strategic planning, which primarily involves System 2 thinking. You develop a strategic plan for the refactoring process, carefully breaking down the monolith into bounded contexts. This step requires thoughtful consideration of the system’s structure and business logic. As part of this planning, you identify key aggregate roots, entities, and value objects within each bounded context (we will do a recap on these terms in Chapters 3 and 4 ), laying the groundwork for a more modular and domain-aligned architecture.
The actual refactoring process is where both System 1 and System 2 thinking truly shine in tandem. You apply System 1 thinking for straightforward refactoring tasks within each bounded context. These might include simple code cleanup, renaming for clarity, or extracting obvious methods. For more complex tasks, you switch to System 2 thinking. This includes defining new interfaces, decoupling dependencies, and ensuring data consistency across the newly defined boundaries. The interplay between quick, intuitive decisions and deeper, more analytical thinking allows for efficient progress while maintaining the integrity of the refactoring effort.
Throughout the refactoring process, continuous review and adaptation are crucial. You regularly review the refactoring progress with your team, using System 1 thinking to identify quick wins and immediate improvements. At the same time, you employ System 2 thinking to address any emerging challenges or changes in requirements. This balanced approach ensures that you can make rapid progress while also adapting to the evolving needs of the project and catching any potential issues before they become significant problems.
By understanding the dual systems of thinking and recognizing common cognitive biases, you can improve your decision-making process during refactoring. Leveraging System 1 for routine tasks and System 2 for complex problem-solving allows for a balanced and effective approach. Always remain vigilant of biases, seek diverse perspectives, and apply deliberate thinking to tackle the complexity inherent in refactoring.
Summary
In this chapter, you discovered tools to help understand and pragmatically approach complexity. You gained a comprehensive understanding of handling modern systems’ complexity by effectively separating and navigating the problem and solution spaces while mitigating biases in decision-making. You learned how to approach the complexity of modern systems, the importance of remaining in the problem space as long as possible, and how thinking about the solution changes from thinking about the problem. Additionally, you explored the differences between System 1 and System 2.
In the next chapter, we will delve into context mapping and strategic patterns. You will learn how to identify and map the various contexts within your domain, understand the relationships between them, and apply strategic patterns to manage these contexts effectively. This will enable you to align your system’s design with its business goals, ensuring a more cohesive and adaptable architecture.