Book review (1/2): Extreme Programming Explained (Second Edition) de Kent Beck y Cynthia Andres
Pues... sí que es extreme, sí
Hoy me incorporo al equipaso de Mercadona Tech y ya me habían soplado que son ultra fanes de XP. Ha llovido desde mi primer (y último hasta la fecha) contacto con Extreme Programming, que fue allá por 2015, teórico, y un poco de refilón (algunas preguntas en los exámenes de Professional Scrum Master y Professional Scrum Developer).
Antes de mi primerito día selling lechugas, quería recordar prácticas, y sobre todo los valores, concretados en principios y los porqués. Intenté hacer un atajo y primero me lei la Extreme Programming Pocket Guide y de ahí salí escandalizado…
…pero LaGenteTM, sabiamente me aconsejó que fuera a por el original, este "Extreme Programming Explained", en especial @jcesarperez:
Y es curioso porque, efectivamente, he salido encantadísimo de la vida, aunque creo que es un approach a la creación del software bastante... valiente, y complicado de hacer correctamente (pero vamos, pretends to be shocked, hacer las cosas bien cuesta trabajo). Estoy deseando probarlo, especialmente en un equipo que tiene pinta de estar tomándoselo bastante en serio.
El libro, por cierto, está para mi gusto genialmente estructurado: te cuenta primero los valores, después principios (la concreción de esos valores en torno al software) y las prácticas de XP, con luego algunos extendidos bastante interesantes alrededor (cómo afecta XP a todos los actores en una empresa, una discusión más larga sobre diseño incremental, testing...). No voy a reproducirlos todos aquí (para eso está el propio libro), pero sí quiero resaltar aquellas cosas que me han sorprendido más.
Hay tanta tela que cortar que lo tengo que dividir en dos entregas.
En ésta:
¿Por qué “extreme”?
La oralidad de XP.
Incremental Design.
¿Por qué "extreme"?
Según el propio Kent Beck, "extreme" aquí se refiere a la pureza: dice que ha destilado aquello que ha hecho o ha visto que se ha hecho que funciona. Pero claramente es extreme también en contraste con cómo se venían haciendo las cosas:
Practices that seemed impossibly extreme five years ago, when the first edition of this book was published [1999!], are now common. Five years from now the practices in this book will probably seem conservative. [p. 21]
Todavía es "extreme" (pero ojalá no lo fuera)
¡Muchas de las propuestas me siguen pareciendo bastante poco convencionales hoy! Me asustan incluso, pero Kent Beck todo esto se lo veía venir. Me gusta mucho que se anticipe y hable precisamente de estas emociones en múltiples partes del libro:
Is about social change (...) giving up the defenses that protect us but interfere with our productivity. It may leave us feeling exposed. [p. 1]
Raise your expectations for accountability and teamwork, then help the team through the inevitable anxiety that comes with change. [p. 57]
Sometimes the desire for more time is a mask worn to protect from the fear of the consequences of getting going. [p. 31]
XP also encourages human contact among the team, reducing the loneliness that is often at the heart of job dissatisfaction. [p. 6]
Y uno de mis fragmentos favoritos porque como mega control freak que soy, me siento totalmente reflejado:
Energized work (...) I'm my own case I think I turn to long work hours as a way of grabbing control in a situation in which I am otherwise out of control. I can't control how the whole project is going (...) but I can always stay later (...) past the point where I have started removing value from the project. [p. 41]
No es casualidad, es que precisamente considera que el objetivo de XP es humanizar el desarrollo de software con todo lo que ello supone, porque con ello también conseguirá una mayor productividad, es decir, humanidad y productividad están en una situación de win-win:
XP is my attempt to reconcile humanity and productivity in my own practice of software development. [p. 3]
XP además es muy prosocial. Hace especial hincapié en las relaciones interpersonales entre todas las personas que intervienen en el hacer del software:
The key to success lies not in self-mortification but in acceptance that we are people in a person-to-person business. [p. 4]
De relaciones interpersonales en software, en realidad, se ha hablado muchísimo. No hay casi libro de software que no cite la mítica frase de Gerald Weinberg, “No matter what they tell you, it's always a people problem". Lo que me resulta sorprendente de XP es integrarlas tanto en el framework de trabajo y la exhaustividad con que las trata.
La oralidad de XP
No a la comunicación escrita
Una de las cosas que más me sorprende de XP, y con la que más me cuesta comulgar, plenamente es su defensa de la comunicación oral frente a la escrita.
Written communication is inherently more wasteful (...) it is a one-way communication. [p. 23]
Maintain only the code and the tests as permanent artifacts. Generate other documents from the code and tests. Rely on social mechanisms to keep alive important history of the project. [p. 66]
Súper a favor de que cualquier documento esté lo más cerca posible del código (generar docs del código, por ejemplo). Pero me cuesta aceptar la idea de depender de "social mechanisms" tanto: la memoria falla, es imprecisa, la gente se va de los equipos… Entiendo que Kent Beck propone crear un clima del que la gente no se quiere ir y en el que mantener viva la historia de un proyecto, pero se pueden ir igual y tengo la sensación de que la barrera de entrada al proyecto es mayor, como por ejemplo cuentan en Your developer won’t get hit by a bus. They’ll get hired by Netflix!
Sticking to the standards evangelized by the community and adding proper documentation (possibly in the form of useful tests) makes onboarding a breeze, which creates more productive developers, which makes hiring more accessible, which reduces your “bus factor.”
Tiene sentido en el marco de humanizar el software, que quieras fomentar la conversación oral, porque esto favorece el tratar las emociones, la empatía... Sin embargo, creo que Beck no es del todo justo con los méritos de la comunicación escrita. Por ejemplo, cuando afirma lo siguiente:
Extensive internal documentation of software is an example of a practice that violates mutual benefit (...). I can see a posible benefit to the future person should the documentation still happen to be valid, but no benefit now. [p. 26]
Sí que veo beneficios en el now: el más directo es que escribir es pensar y cristalizar. Como se menciona en Who Builds a House Without Drawing Blueprints?: “Writing is nature's way of letting you know how sloppy your thinking is”.
Aunque en justicia, el comentario de Beck, como apuntó mucha gente en el hilo de Twitter al principio de esta newsletter, quizá va referido sobre todo a la parte de "extensive" y al contexto de la época (por ejemplo, los grandes documentos de especificaciones en un waterfall). Además, para él esa cristalización son los tests funcionales, los unitarios, y el propio código. Still, pienso mucho en la línea de lo que se cuenta en Who Builds a House Without Drawing Blueprints?:
Programmers who advocate writing tests before writing code often believe those tests can serve as a specification. Writing tests does force us to think, and anything that gets us to think before coding is helpful. However, writing tests in code does not get us thinking above the code level. We can write a specification as a list of high-level descriptions of tests the program should pass essentially a list of properties the program should satisfy. But that is usually not a good way to write a specification, because it is very difficult to deduce from it what the program should or should not do in every situation.
Bien de conversación
Otra cosa que contradice totalmente mi intuición es cuan intensiva propone que sea ese hablar entre compañeros:
People evaluating XP teams should understand what an effective team looks like. This may differ from other teams they have seen. For example, talking and working go together on an XP team. The hum of conversation is a sign of health. Silence is the sound of risk pilling up. [p. 79]
A mi me ha tocado hacer mucho más tener que pedir a un equipo que por favor no me montaran el "Hablar por Hablar", que lo contrario. Pero el amigo Kent Beck, que ha pensado muy fuerte todo esto, tiene respuesta para todo:
Perhaps this sounds like a perpetual coffee klatch with everyone sitting around 'caring and sharing' and no one doing anything. Other values held by the team keep this from happening. [p. 18]
The signature practice: pair programming
De hecho, quizá la práctica más popular desde fuera de XP es el pair programming. Pero que lo que propone Beck es mucho más que practicarlo de cuando en cuando, sino al revés, solo de cuando en cuando ve a programar tú solo:
Write all production programs with two people sitting at one machine. [p. 42]
Pairing doesn't mean that you can't think alone. People need both companionship and privacy (...). You can even prototype alone and still respect pairing. However, this is not an excuse to act outside of the team (...) bring the resulting idea, not the code, back to the team. With a partner, you'll reimplement it quickly. The results will be more widely understood. [p. 42]
Este último matiz me pareció muy interesante, me hizo aceptar la práctica con mucho más convencimiento, porque creo que en el pair programming como double check y difusor de conocimiento, pero no creo mucho en el pensamiento colaborativo como mecanismo principal para resolver algo. Siento que me funciona mucho mejor alternar reflexiones / exploraciones individuales con puestas en común, que intentar algo (que se me hace tan raro) como pensar en compañía, verbalmente. En mis equipos normalmente, previo al coding de features no triviales, hacemos un documento de análisis sobre el que colaboramos (como conté aquí: ‘Mención especial, "The bottleneck trap"‘).
El propio Beck afirma que, lógicamente, este pair programming tan intensivo cansa, que no puedes estar 8 horas de trabajo pairing (¡aunque el propone 6!), pero que merece la pena por múltiples motivos: mantenerte en la tarea, brainstorming, obligar a clarificar, desatascar al compañero y ser más responsable. Todos los que hemos jugado al Among Us sabemos que mucho de esto es cierto.
Me sorprende también las rotaciones que propone:
I like to program with someone new every couple of hours. [p. 42]
Que aquí ya me vuelvo loco... ¿cómo se gestionan los cambios de contexto en las tareas? ¿Será porque tienen que tener granularidades muy pequeñas?
¿Open offices ok?
Lógicamente, si buscas que haya una conversación siempre en marcha, necesitas una open office:
Sit together (...). Develop in an open space big enough for the whole team. [p. 37]
Sin embargo, me pregunto cómo casa todo esto con lo que lei en su día en el también mítico Peopleware sobre las open offices:
...without warning, open-plan seating was upon us like a plague upon the land. The advocates of the new format produced not one shred of evidence that effectiveness would not be impared.
Curiosamente en Peopleware sí que hay varias referencias a varios estudios al respecto, que no dejan en buen lugar a la open office.
Se ve cierta correlación del performance con la "quietud", "privacidad" y la ausencia de interrupciones. En cualquier caso, en ese estudio no se estaban aplicando el resto de prácticas de XP: aplicar todas las prácticas es lo que hace que XP funcione plenamente, por toda una serie de sinergias entre ellas.
Socialización, pero lógicamente hay límites
Beck trata incluso qué pasa si hay incomodidades haciendo pair programming, y hasta incluso, si surgen sentimientos:
Pairing and personal space. When programmers aren't emotionally mature enough to separate approval from arousal, working with a person of the opposite gender can bring up sexual feeling that are not in the best interest of the team. [p. 43]
Se siente un poco distópico el tratarlo así, pero es que es verdad que estas cosas pasan, que está bien hablarlas, y no deja de ser cierto lo que comenta al respecto.
Otra de mis partes favoritas del libro ha sido este fragmento:
Fussing about the constraints distracts you from your goals (...). If you have six weeks to get a project done, the only thing you control is your own behavior (...). You can't control others' expectations. You can tell them what you know (...) so their expectation have a chance of matching reality. It's not my job to manage someone else expectations. [p. 5]
Siempre que he currado como líder de equipos he pensado que mi trabajo principal es precisamente gestión de expectativas:
Este fragmento ha sido de lo más liberador que he leído en mucho tiempo.
Incremental design
Este es otro de los puntos que me resultaron chocantes al leer la pocket guide, pero que me ha quedado muchísimo más claro al leer este libro.
Invertir mucho en diseño al principio de un proyecto/feature viene de distintos estudios a finales de los locos años 80. Por ejemplo en Code Complete de Steve McConnelll encontramos lo siguiente:
If you can prevent defects or detect and remove them early, you can realize a significant schedule benefit. Studies have found that reworking defective requirements, design, and code typically consumes 40 to 50 percent of the total cost of software development (Jones 1986b; Boehm 1987a). As a rule of thumb, every hour you spend on defect prevention will reduce your repair time "3 to 10 hours" (Jones 1994). In the worst case, reworking a software-requirements problem once the software is in operation typically costs 50 to 200 times what it would take to rework the problem in the requirements stage (Boehm and Papaccio 1988). Given that about 60 percent of all defects usually exist at design time (Glib 1988), you can save enormous amounts of time by detecting defects earlier than system testing.
La idea del incremental design que propone XP, por el contrario, es no invertir mucho tiempo en diseño upfront, porque lo contrario es un ejercicio especulativo:
Incremental design suggests that the most effective time to design is in the light of experience. [p. 52]
One factor to take into consideration in deciding when to design is the value available through the different strategies. [p. 106]
Tiene muchísimo sentido para mí esto, pero, ¿cómo sabes ante qué problema/situación estás a priori, sin diseñar y sin la experiencia? Aunque luego lo aclara: se trata de invertir lo justo en diseño inicial para obtener el suficiente feedback para otra ronda.
Beck, además, cuestiona esos estudios previos que parecen afirmar que siempre cuesta más arreglar los defectos con el tiempo (aunque lo cierto es que lo hace sin data) :/
For an assumption that shaped software development orthodoxy for decades, the increasing cost of change over time received little scrutiny. This assumption may no longer be valid [p. 52]
Refactorings can occur at any level of scale. Few design decisions are difficult to change once made. [p. 53]
XP teams work hard to create conditions under which the cost of changing the software doesn't rise catastrophically. [p. 52]
Unfortunately, design in software has been shackled by metaphors from physical design activities (...) in software, however, reversing a day's work is trivial. [p. 104]
Luego matiza que no es tan trivial:
Require habilidad el saber hasta dónde llegar:
There is an art to designing just enough to get feedback, and then using that feedback to improve the design enough to get the next round of feedback. [p. 104]
Hay que partir grandes cambios para que cada semana, aún así, se entregue funcionalidad:
Sometimes the team can't make a design improvement in a week and still deliver new functionality. Part of incremental design is figuring out how to stage design improvements (...). As you touch the existing code, concentrate those assumptions in as few places as possible. Eventually, the job (...) will fit into a week. Such long-running changes may seem to cost more than stopping development and making the change all at once. (...) Design is in service of a trust relationship between technical and business people. Weekly delivery of requested functionality is the cornerstone of that relationship. [p. 108]
Y por supuesto, también require disciplina:
Most often, I didn't improve the design because I was focused to narrowly on the problem of adding one more feature to the system. [p. 108]
También hace una aclaración muy importante, que yo desde luego necesitaba:
Some of the teams who read and applied the first edition of this book didn't get the part of the message about the last responsible moment. They piled story on story (...). Without daily attention to design, the cost of changes does skyrocket. [p. 52].
Este tipo de aclaraciones ponen de relieve algo que nos afecta mucho en este sector (me imagino que en todos): oir los titulares y quedarse con una idea errónea. Realmente los matices luego son tan potentes que cambian bastante la idea, como por ejemplo comentaba en Ask HN: How bad should the code be in a startup?
Next time on… this substack:
XP >>> Taylorismo.
Un problema de incentivos.
Offshore development: ¿cómo competir en un mercado global? (sí, XP también se mete aquí).
Conclusión