Saturday, January 25, 2020

The first step in refactoring

Bfore you start refactoring, make sure you have a solid suite of tests. These tests must be self-checking.

Martin Fowler, "Refactoring: A First Example", in Refactoring: Improving the Design of Existing Code (2nd Edition), 5.

The purpose of refactoring

Given that the program works, isn't any statement about its structure merely an aesthetic judgment, a dislike of "ugly" code? After all, the compiler doesn't care whether the code is ugly or clean. But when I change the system, there is a human involved, and humans do care. A poorly designed system is hard to change — because it is difficult to figure out what to change and how these changes will interact with the existing code to get the behavior I want. And if it is hard to figure out what to change, there is a good chance that I will make mistakes and introduce bugs.

Thus, if I'm faced with modifying a program with hundreds of lines of code, I'd rather it be structured into a set of functions and other program elements that allow me to understand more easily what the program is doing. If the program lacks structure, it's usually easier for me to add structure to the program first, and then make the change I need.

Let me stress that it's these changes that drive the need to perform refactoring. If the code works and doesn't ever need to change, it's perfectly fine to leave it alone. It would be nice to improve it, but unless someone needs to understand it, it isn't causing any real harm. Yet as soon as someone does need to understand how that code works, and struggles to follow it, then you have to do something about it.

Martin Fowler, "Refactoring: A First Example", in Refactoring: Improving the Design of Existing Code (2nd Edition), 4-5.

Any fool can write code that a computer can understand. Good programmers write code that humans can understand.

Martin Fowler, "Refactoring: A First Example", in Refactoring: Improving the Design of Existing Code (2nd Edition), 10.

Saturday, January 18, 2020

Refactoring versus restructuring

Developers sometimes co-opt terms that sound cool and make them into broader synonyms, as is the case for refactoring. As defined by Martin Fowler, refactoring is the process of restructuring existing computer code without changing its external behavior. For many developers, refactoring has become synonymous with change, but there are key differences.

It is exceedingly rare that a team refactors an architecture: rather, they restructure it, making substantive changes to both structure and behavior. Architecture patterns exist in part to make certain architectural characteristics primary in an application. Switching patterns entails switching priorities, which isn't refactoring. For example, architects might choose an EDA for scalability. If the team siwtches to a different architectural pattern, it likely won't support the same level of scalability.

Neal Ford, Rebecca Parsons & Patrick Kua, "Building Evolvable Architectures", in Building Evolutionary Architectures: Support Constant Change, 99.

Retrofitting existing architectures

Adding evolvability to existing architectures depends on three factors:

Appropriate coupling and cohesion

Beyond the technical aspects of coupling, architects must also consider and defend the functional cohesion of the components of their system. For example, some business problems are more coupled than others, such as in the case of heavily transactional systems. Trying to build an extremely decoupled architecture that is counter to the problem is unproductive.

Understand the business problem before choosing an architecture.

While this advice seems obvious, we constantly see teams that have chosen the shiniest new architectural pattern rather than the most appropriate one suffer. Part of choosing an architecture lies in understanding where the problem and physical architecture come together.

Engineering practices

While Continuous Delivery practices don't guarantee evolutionary architecture, it is almost impossible without them.

The biggest single common impediment to building evolutionary architecture is intractable operations. If developers cannot easily deploy changes, all parts of the feedback cycle are hampered.

Fitness functions

We encourage architects to start thinking of all kinds of architectural verification mechanisms as fitness functions, including things they have previously considered ad hocly. For example, many architectures have a service-level agreement around scalability and corresponding tests. They also have rules around security requirements, with accompanying verification mechanisms. Architects often think of these as separate categories, but both intents are the same: verify some feature of the architecture. By thinking of all architectural verification as fitness functions, there is more consistency when automation and other beneficial synergistic interactions are defined.

Neal Ford, Rebecca Parsons & Patrick Kua, "Building Evolvable Architectures", in Building Evolutionary Architectures: Support Constant Change, 97-99.

Building evolvable architectures

Many of the concepts we discussed aren't new ideas, but rather viewed through a new lens. For example, testing has existed for years, but not with the fitness function emphasis on architectural verification. Continuous Delivery defined the idea of deployment pipelines. Evolutionary architecture shows architects the real utility of that capability.

Many organizations pursue Continuous Delivery practices as a way to increase engineering efficiency for software development, a worthy goal in itself. However, we're taking the next step, using those capabilities to create something more sophisticated — architectures that evolve with the real world.

Mechanics

Architects can operationalize these techniques for building an evolutionary architecture in three steps:

  1. Identify dimensions affected by evolution
  2. Define fitness function(s) for each dimension
  3. Use deployment pipelines to automate fitness functions

[...] Software suffers from the unknow unknows problem: developers cannot anticipate everything. [...] While some fitness functions will naturally come to light at the beginning of a project, many won't reveal themselves until an architectural stress point appears. Architects must vigilantly watch for situations where nonfunctional requirements break and retrofit the architecture with fitness functions to prevent future problems.

Neal Ford, Rebecca Parsons & Patrick Kua, "Building Evolvable Architectures", in Building Evolutionary Architectures: Support Constant Change, 95-96.

Wednesday, January 8, 2020

Logs em formato JSON com Python

Python possui um módulo de logging bastante robusto já embutido em sua biblioteca padrão. Esse módulo disponibiliza muita coisa pronta para que qualquer pessoa comece a incluir logs em sua aplicação sem grande esforço. Não obstante, o módulo é também altamente configurável, permitindo personalizar a estrutura de handling dos logs, o formato das mensagens, entre outras coisas.

Em algumas situações, pode ser interessante que a mensagem de log gerada seja um JSON bem formatado, contendo informações sobre o fluxo da aplicação em formato chave-valor. Isto é, em vez de emitir logs esparsos, que teriam que ser agregados para dar visão geral do fluxo, poderíamos ter um único log em formato JSON impresso ao final da execução de determinado fluxo (independentemente desse fluxo ter terminado de forma bem sucedida ou não). Essa abordagem facilita não somente a busca por mensagens específicas (usando ferramentas como o CloudWatch Logs Insights) mas também o próprio processo de depuração de problemas, concentrando as informações necessárias num formato bem estruturado.

Em Python, podemos gerar strings JSON a partir de dicionários. Usando as cláusulas try/except/finally, consequimos também garantir a impressão dos logs qualquer que seja o resultado da execução do fluxo contido no bloco de tratamento de exceções. A maior dificuldade é repetir todo esse boilerplate nos pontos em que é necessário aplicar o log JSON. Podemos então lançar mão de mais um recurso da linguagem a fim de evitar essa repetição: decoradores. O Gist a seguir mostra uma maneira de conectar todas essas ideias para construir um decorador que, ao ser aplicado a um método/função, permite construir facilmente um log JSON que será impresso ao final da execução desse método/função, ainda que um erro aconteça durante a execução.

Wednesday, January 1, 2020

Evolutionary database design

In Chapters 1 and 4, we discussed the architectural quantum boundary concept definition: the smallest architectural deployable unit, which differs from traditional thinking about cohesion by encompassing dependent components like databases. The binding created by databases is more imposing than traditional coupling because of transactional boundaries, which often define how business processes work. Architects sometimes err in trying to build an architecture with a smaller level of granularity than is natural for the business. For example, microservices architectures aren't particularly well suited for heavily transactional systems because the goal service quantum is so small. Service-based architectures tend to work better because of less strict quantum size requirements.

Architects must consider all the coupling characteristics of their application: classes, package/namespace, library and framework, data schemas, and transactional contexts. Ignoring any of these dimensions (or their interactions) creates problems when trying to evolve an architecture. In physics, the strong nuclear force that binds atoms togheter is one of the strongest forces yet identified. Transactional contexts act like a strong nuclear force for architecture quanta.

While systems often cannot avoid transactions, architects should try to limit transactional contexts as much as possible because they form a tight coupling knot, hampering the ability to change components or services without affecting others. More importantly, architects should take aspects like transactional boundaries into account when thinking about architectural changes.

As discussed in Chapter 8, when migrating a monolithic architectural style to a more granular one, start with a small number of large services first. When building a greenfield microservices architecture, developers should be diligent about restricting the size of service and data contexts. However, don't take the name microservices too literally — each service doesn't have to be small, but rather capture a useful bounded context.

When restructuring an existing database schema, it is often difficult to achieve appropriate granularity. Many enterprise DBAs spend decades stitching a database schema togheter and have no interest in performing the reverse operation. Often, the necessary transactional contexts to support the business define the smallest granularity developers can make into services. While architects may aspire to create a smaller level of granularity, their efforts slip into inappropriate coupling if it creates a mismatch with data concerns.

Age and quality of data

Before trying to build an evolutionary architecture, make sure developers can evolve the data as well, both in terms of schema and quality. Poor structure requires refactoring, and DBAs should perform whatever actions are necessary to baseline the quality of data. We prefer fixing these problems early rather than building elaborate, ongoing mechanisms to handle these problems in perpetuity.

Legacy schemas and data have value, but they also represent a tax on the ability to evolve. Architects, DBAs, and business representatives need to have frank conversations about what represents value to the organization — keeping legacy data forever or the ability to make evolutionary change. Look at the data that has true value and preserve it, and make the the older data available for reference but out of the mainstream of evolutionary development.

Neal Ford, Rebecca Parsons & Patrick Kua, "Evolutionary Data", in Building Evolutionary Architectures: Support Constant Change, 91-93.