Ext4 filesystem has no space left on device? You liar!

So, you wake up one day, and find that one of your programs, starts to complainig about “No space left on device”:
Next thing (Obviously, duh?) is to see what happened, so you fire up du -h /tmp right?:
$ du -h /tmp
Filesystem Size Used Avail Use% Mounted on
/dev/mapper/zkvm1-root 6.2G 4.6G 1.3G 79% /

Wait, what? there’s space there! How can it be? In all my years of experience (+15!), I’ve never seen such thing!
Gods must be crazy!? or is it a 2020 thing?

$ touch /tmp
touch: cannot touch ‘/tmp/test’: No space left on device

After shamelessly googling/duckducking/searching, I ended up at https://blog.merovius.de/2013/10/20/ext4-mysterious-no-space-left-on.html
but alas, that was not my problem, although… perhaps too many files?, let’s check with du -i this time:
$ du -i /tmp
`Filesystem Inodes IUsed IFree IUse% Mounted on
/dev/mapper/zkvm1-root 417792 417792 0 100% /

Because I’m super smart I’m not, I now know where my problem is, too many files!, time to start fixing this…
After few minutes of deleting files, moving things around, bind mounting things, I landed with the actual root cause:
Tons of messages waiting in /var/spool/clientmqueue to be processed,
I decided to delete some, after all, I don’t care about this system’s mails… so find /var/spool/clientmqueue -type f -delete does the job, and allows me to have tab completion again! YAY!.
However, because deleting files blindly is never a good solution, I ended up in the link from above, the solution was quite simple:
$ systemctl enable --now sendmail

After a while, root user started to receive system mail, and I could delete them afterwards :)
In the end, very simple solution (In my case!) rather than formatting or transfering all the data to a second drive, formatting & playing with inode size and stuff…
Filesystem Inodes IUsed IFree IUse% Mounted on
/dev/mapper/zkvm1-root 417792 92955 324837 23% /
Et voilà, ma chérie!

This is a very long post, just to say:
ext4 no space left on device can mean: You have no space left, or you don’t have more room to store your files.
openSUSE Projects Support Hacktoberfest Efforts
The openSUSE community is ready for Hacktoberfest, which is run by Digital Ocean and DEV that encourages people to make their first contributions to open source projects. The openSUSE + LibreOffice Virtual Conference will take place during Hacktoberfest and is listed as an event on the website. The conference will have more than 100 talks about open source projects ranging from documentation to the technologies within each project.
Some resources available to those who are interested in getting started with openSUSE Projects during Hacktoberfest are:
Open Build Service
The Open Build Service is a generic system to build and distribute binary packages from sources in an automatic, consistent and reproducible way. Contributors can release packages as well as updates, add-ons, appliances and entire distributions for a wide range of operating systems and hardware architectures.
Known by many open source developers simply as OBS, the Open Build Service is a great way to build packages for your home repository to see if what is built or changes works. People can always download the latest version of your software as binary packages for their operating system. The packages can be build for different operating system. Once they are connected to your repository, you can serve them with maintenance or security updates and even add-ons for your software.
Some specific items to look at for OBS are the open-build-service-api and the open-build-service-connector.
The OBS community can be found in IRC on the channel #opensuse-buildservice. Or you can join the mailing list opensuse-buildservice@opensuse.org.
Repository Mirroring Tool
This tool allows you to mirror RPM repositories in your own private network. Organization (mirroring) credentials are required to mirror SUSE repositories. There is end-user documentation for RMT. The man pages for rmt-cli is located in the file MANUAL.md. Anyone who would like to contribute to RMT can view how to do so in the contribution guide.
openQA
openQA is an automated test tool for operating systems. It is used by multiple projects to test for quality assurance of software changes and updates. There are multiple resources to get started with to learn how the software works.
Documentation can be found https://open.qa/docs/ and https://open.qa/api/testapi/. There are tutorial videos on Youtube that go in depth on how to use the software. Quickstarts to setup your local instance are available at https://open.qa/docs/#bootstrapping and https://youtu.be/lo929gSEtms (livestream recording)
Repositories can be found at:
- webUI + scheduler: https://github.com/os-autoinst/openQA
- backend: https://github.com/os-autoinst/os-autoinst
- testcases and needles for openSUSE: https://github.com/os-autoinst/os-autoinst-distri-opensuse and https://github.com/os-autoinst/os-autoinst-needles-opensuse
To Reach the community, go to the #opensuse-factory channel on freenode.net IRC
Uyuni Project
Named after the largest salt flat in the world, Uyuni is a configuration and infrastructure management tool that saves people time and headaches when managing updates of tens, hundreds or even thousands of machines.
There have been many talks about Uyuni and many can be found on the project’s Youtube Page. Presentation slides a can be found on slideshare. There is also information about getting started for developers and translators at https://github.com/uyuni-project/uyuni/wiki and https://github.com/uyuni-project/uyuni/wiki/Translating-Uyuni-to-your-language.
A quick setup guide is available at https://github.com/uyuni-project/sumaform and people can start Hacktoberfest issues.
Hacktoberfest participants can communication with members of the Uyuni Project through Gitter chat or the mailing lists.
SAFE VOTE: Minimizando propagação do COVID-19 em eleições.

Existe muita polêmica sobre os mesários nas eleições em função do COVID-19. Mas no meu ponto de vista particular, não podemos desprezar o contato a urna eletrônica por diversas pessoas e seu respectivo problema. O controle da higienização das urnas é um complexo problema, pois um erro humano pode custar muito caro.
Enfim, pensando neste cenário para descontrair um pouco, imaginei utilizar um pouco da tecnologia de visão computacional para evitar o contato com equipamento. Pois podemos atualmente detectar as mão e os dedos assim evitando contato. Uma interface deve ser intuitiva para facilitar a votação, mas a prova de conceito desenvolvida em 3 horas demonstra a viabilidade e talvez solução para vários contextos problemáticos. Veja a seguir um vídeo demonstrativo.
El encuentro #esLibre2020 se celebrará de manera virtual el 18 y 19 de septiembre
esLibre es un evento relacionado con el software libre que se celebra en España y que este año celebra su segunda edición de manera virtual
![]()
La inesperada pandemia del Covid-19 ha traído muchos trastornos a nuestro día a día. Cambio en las relaciones sociales, cambio de hábitos, adaptarse a nuevas circunstancias, etc…
Entre esos cambios de hábitos, están la reducción de asistentes a eventos, ya sea teatro, conciertos, eventos sociales, o asistencia a charlas y conferencias. Me centro en estas últimas y concretamente las relacionadas con el software libre.
Muchas de esas conferencias o charlas se han cancelado hasta más adelante, para no poner en riesgo la salud de los asistentes (me viene a la mente el Akademy-es) y otros eventos han modificado su planteamiento para realizarlo de manera virtual on-line (por ejemplo el recientemente celebrado Akademy)
Por un lado, dejamos de juntarnos e interactuar en persona y compartir charla, comida y cerveza… pero por otro se llega a más gente, que por diversos motivos no puede asistir a actos presenciales que se celebran en otros países.
Ahora esas reuniones llegan a todo el mundo de manera instantánea. Y desde Chile a la India, pasando por Europa, África y Oceanía, entusiastas del tema tratado pueden disfrutar y aprender de aquello que les apasiona.
Así que aprovechemos esas tecnologías libres que nos ofrecen poder acercarnos y producir sinergias y participemos de esos eventos en línea. Como por ejemplo esLibre2020 que se celebrará el próximo 18 y 19 de septiembre desde España para todo el mundo.
Y tu te preguntarás ¿Qué es esLibre? Veamos cómo definen el evento:
esLibre es un encuentro de personas interesadas en las tecnologías libres, enfocado a compartir conocimiento y experiencia alrededor de las mismas.
¿Te interesa esa definición? ¿Te ves incluido o incluida en ella? Entonces esLibre es para ti ¡y no debes perdértela!
La primera edición se celebró en Granada, y para esta edición como ya he dicho, se ha optado por la reconversión del plan original en un evento en línea.
Así que reserva esas fechas, que además es el día de la libertad del software (que buena manera de celebrarlo) y echa un vistazo al programa interesante de charlas y talleres que han organizado y disponte a disfrutar y aprender.
Muchos ponentes, muchas temáticas, muchos aspectos tratados, pero todo desde el punto de vista del software libre. Seguro que hay alguna charla o taller que te interesa, y si no lo hay te invito a que te dejes sorprender y descubras nuevas temáticas que quizás sean de tu interés…
Volveremos a juntarnos, volveremos a asistir codo con codo a actos, pero de momento esta es buena alternativa. Aunque así no podremos presumir de pegatinas en nuestros equipos… corriendo software libre!
Enlaces de interés
Tarde del tercer día de Akademy 2020 en línea
Ya ha finalizado el evento más importante de la Comunidad KDE Internacional pero en el blog seguimos repasando cómo fueron las ponencias. Bienvenidos a la tarde del tercer día de Akademy 2020 en línea, donde se habló de un montón de proyectos y tecnologías: Kdenlive, Wikidata, OpenStreeMap, MyGNUHealth, móviles, Kirigami, etc.
Tarde del tercer día de Akademy 2020 en línea
Sigo empezando los artículos dedicados a Akademy 2020 con este vídeo de bienvenida… me ha encantado la diversidad cultural que nos muestra.
Al igual que la mañana del domingo, tenemos dos salas simultáneas donde los miembros de la Comunidad siguen compartiendo conocimientos. De esta forma hablaremos de la Room 1 y la Room 2.
No obstante la tarde empieza con una charla muy especial que es la de agradecimientos a los patrocinadores del evento: Canonical, KDAB, MBition, openSUSE, GitLab, Froglogic, Collabora, CodeThink, FELGO, DorotaC.eu, The Qt Company, Pine64 y Tuxedo por su generosidad gracias a la cual Akademy es posible.
De esta forma nos encontramos en la Room 1 ponencias como:
- Creating a Convergent Application Following the KDE Human Interface Guidelines donde Dimitris Kardarakos habló sobre la creación de una aplicación convergente siguiendo las directrices de la interfaz humana de KDE utilizando Kirigami, demostrando cómo una aplicación puede verse igual de bien en el escritorio y en el móvil.
- Getting into KWin and Wayland de Aleix Pol en el que explicó cómo los colaboradores podían involucrarse en el desarrollo de la experiencia Wayland de KDE.

- Introducing Fedora KDE donde Neal Gompa explicó cómo comenzó y qué lo hace especial dentro de Fedora.
- Using Wikidata and OpenStreetMap en la que Volker Krause mostró cómo, utilizando los datos de Wikidata y OpenStreetMap, era posible hacer aplicaciones más inteligentes.
- Next Generation Application Management donde David Edmundson y Henri Chain co-organizaron una charla sobre la Gestión de Aplicaciones de Próxima Generación y explicaron cómo usando cgroups, los desarrolladores podrían contribuir a hacer todo asombroso.
- API Design and QML charla técnica por parte de Carson Black que habló sobre el diseño de la API y el QML.
Mientras que para la Room 2 nos encontramos con:
- Konquering the Droids donde Nicolas Fella explicó que para que KDE siga siendo relevante KDE necesita expandirse desde su tradicional espacio de escritorio hacia el mundo móvil y que lo está haciendo poco a poco.
- MyGNUHealth: GNU Health Goes Mobile with KDE & Kirigami en el que el doctor Luis Falcón nos habló de un sistema de información hospitalaria y de salud libre que ha sido desplegado en muchos países alrededor del mundo, desde pequeñas clínicas hasta grandes implementaciones de salud pública nacional.

- Change Management ponencia de Aniqa Khokhar nos introdujo en la Gestión del Cambio y nos ayudó a aprender a aceptar los cambios y los recién llegados a KDE.
- Open Source Compliance charla de Catharina Maracke en la que habló a los asistentes sobre el cumplimiento del código abierto. Catharina nos contó cómo en el complejo mundo actual de cumplimiento de las licencias de OSS, es muy importante conocer los fundamentos de los derechos de autor y las estructuras de licencias, así como algunos de los consejos y trucos relevantes para las licencias de OSS más comunes.
- Kdenlive: A Journey of Being a Leading Open Source Video Editor ponencias de Massimo Stella que nos contó sobre su experiencia con Kdenlive y nos mostró un video de las nuevas capacidades de Kdenlive y proporcionó una demostración en vivo de las nuevas características del poderoso software de edición de video de KDE.
- System Settings: Behind the Scene Benjamin Port explicó cómo la configuración del sistema de plasma ha sido recientemente portada a KConfigXT y las ventajas obtenidas con el cambio de la configuración del sistema.
Cierre de Akademy 2020 con Nuritzi Sánchez

Tal y como ya comenté en un artículo especial, el cierre de Akademy 2020 lo realizó Nuritzi Sánchez en la que habló de algunas de las iniciativas en las que participa el KDE que le ayudan a convertirse en una comunidad más resistente, al tiempo que señaló las áreas de oportunidad.
También exploró temas relacionados con la construcción de comunidades más diversas e inclusivas, incluida la comunicación en colaboración, e ideas para la divulgación.
Material audiovisual Akademy 2020 en línea
Una de las cosas positivas de esta Akademy es que todo el material debe ser emitido digitalmente, lo cual hace que ya puede estar listo para ser compartido en diferido, aunque sea sin editar.

De esta forma, en caso de que te lo hayas perdido, las charlas de hoy ya están disponibles en línea en tres bloques – uno para la mañana y dos para cada una de las habitaciones utilizadas por la tarde. También se ha grabado grabado todas las charlas por separado y pronto podrás verlas en las plataformas de vídeo disponibles de KDE.
Prose linting with Vale and Emacs
I have set myself the goal to improve my writing. I read some books and articles on the topic, but I am also looking for real-time feedback. I am not a native english speaker.
I found about Grammarly on twitter, but there is no way I will send my emails and documents to their server as I type. That is how I started to look for an offline solution.
I found proselint but it seems inactive since 2018. As I tried to integrate it with Emacs, I learned about write-good mode. This Emacs mode has two flaws:
- The implementation is too “simple” (regexps)
- The integration works like a full Emacs mode. Mixing the linting with presentation.
Through those projects, I learned about the original article 3 shell scripts to improve your writing, or “My Ph.D. advisor rewrote himself in bash.”.
I found a more sophisticated and extensible tool called write-good, implemented in Javascript/node, which means I will not be able to package it.
I decided to try to write one. I found the Go library prose. It allows to iterate over tokens, entities and sentences. Iterating over the tokens gives access to tags:
for _, tok := range doc.Tokens() {
fmt.Println(tok.Text, tok.Tag, tok.Label)
// Go NNP B-GPE
// is VBZ O
// an DT O
// ...
}
For example, the text “At dinner, six shrimp were eaten by Harry” produces the following tags:
Harry PERSON At IN dinner NN , , six CD shrimp NN were VBD eaten VBN by IN Harry NNP
The combination VBD (verb, past tense )and VBN (verb, past participle) can be used to detect passive voice, one of the guidelines of “good-write”.
Soon I figured out that the tokens do not give access to the locations. I started to see who is using the code, looking for examples.
I realized the author of the library uses the library to power vale, a prose linter implemented in go. What I was trying to write.
The vale documentation revealed the tool is more than I was looking for. It includes write-good definitions as part of its example styles. There are examples for Documentation CI which include how Gitlab, Linode and Homebrew use it to lint their documentation. It even has a Github action.
Nothing left other than to integrate with Emacs. There is no need to write a full mode for that. A simple Flycheck checker should do. Turns out, it already exists, but I could not make it work.
The existing Emacs checker uses vale JSON output (--output JSON), which gives access to all details of the result. We can write the simplest checker from scratch, by recognizing patterns with --output line:
(flycheck-define-checker vale "A checker for prose" :command ("vale" "--output" "line" source) :standard-input nil :error-patterns ((error line-start (file-name) ":" line ":" column ":" (id (one-or-more (not (any ":")))) ":" (message) line-end)) :modes (markdown-mode org-mode text-mode) ) (add-to-list 'flycheck-checkers 'vale 'append)
Note that for this to work, you need vale in your PATH. I packaged it in the Open Build Service. You need also a $HOME/.vale.ini or in the root of your project:
StylesPath = /usr/share/vale/styles Vocab = Blog [*.txt] BasedOnStyles = Vale, write-good [*.md] BasedOnStyles = Vale, write-good [*.org] BasedOnStyles = Vale, write-good
And with this Emacs works:
Due to --output line not providing severity, every message shows as error.
I am looking forward to integrate vale in some documentation, develop custom styles and why not, investigate and fix the original flycheck-vale project.
Also pending is to expand the configuration to work with my Emacs based mail client, which should be a matter of hooking into mu4e compose mode.
While writing this post, I had to fix the unintended use of passive voice tens of times. Valuable feedback.
Bomber, un juego arcade para Linux
Hoy me apetece seguir presentando algunos juegos de la división más lúdica y divertida de KDE, que aunque no está en la página oficial de KDE Games, si que está en la de aplicaciones, como lo estaba Killbots. Hoy ha llegado el turno a Bomber, un juego estilo arcade para Linux donde debemos destruir todos los edificios y avanzar al siguiente nivel.
Bomber, un juego arcade para Linux
Ya han pasado por este humilde blog un buen número de juegos de la división KDE Games como los recientes Kiriki, LsKat o KPatience o los pasados Kbounce, KSnakeDuel, Kmines, KBreakout, KTuberling, Granatier, KSudoku, KGoldrunner, Kolor Lines (o Klines), KBlocks, Bovo, Kapman, Knights, Palapeli, KSquares, KBlackbox, KShinsen o Kubrick.
Hoy toca hablar de Bomber es un juego de arcade para un solo jugador. El jugador está invadiendo varias ciudades en un avión que está disminuyendo en altura.
El objetivo del juego es destruir todos los edificios y avanzar al siguiente nivel. Cada nivel se hace un poco más difícil aumentando la velocidad del avión y la altura de los edificios.

En realidad es como los clásicos Galaxian o Galaga pero invirtiendo los términos, el que se mueve sin control por parte del jugador es su nave, no la de los enemigos.
El juego es una creación John-Paul Stanford <jp@stanwood.org.uk> y tiene la posibilidad de poner pieles para variar el aspecto del mismo.
Más información: KDE Apps
¿Y cómo se instala?
Al ser un juego de la rama de KDE la instalación es sumamente sencilla. Básicamente debemos abrir una sesión de la consola y escribir:
En KDE Neon, Kubuntu y Linux Mint: $sudo apt install bomber
En openSUSE: $sudo zypper bomber
En Mageia (gracias a Hurr) tenéis 3 opciones:
$ sudo dnf in bomber
o
$ sudo dnf install bomber
o
$ sudo urpmi bomber
[… comenta y añadimos cómo se instala en tu distribución favorita]
Actualización de septiembre del 2020 de KDE Frameworks
Hoy toca entrada recurrente ya que llegamos a la actualización mensual de rigor que demuestra que los desarrolladores de KDE no dejan de trabajar ni durante su encuentro anual: Akademy. Así que se congratulan en anunciar la actualización de septimebre del 2020 de KDE Frameworks. Con esta se llega a la versión 5.74, un suma y sigue de compromiso y constancia que no parece que tenga un final cercano.
Actualización de septiembre del 2020 de KDE Frameworks

A pesar de que para los usuarios corrientes esta noticia sea algo confusa ya que no se trata de realzar una nueva aplicación ni de una nueva gran funcionalidad del escritorio, el desarrollo de KDE Frameworks tiene repercusiones directas en él a medio y largo plazo.
La razón de esta afirmación es que KDE Frameworks es básicamente la base de trabajo de los desarrolladores para realizar sus aplicaciones, es como el papel y las herramientas de dibujo para un artista: cuanto mejor sea el papel y mejores pinceles tenga, la creación de una artista será mejor.
De esta forma, las mejoras en KDE Frameworks facilitan el desarrollo del Software de la Comunidad KDE, haciendo que su funcionamiento, su estabilidad y su integración sea la mejor posible.
El pasado domingo 6 de sepriembre de 2020 fue lanzado KDE Frameworks 5.74, la nueva revisión del entorno de programación sobre el que se asienta Plasma 5, el escritorio GNU/Linux de la Comunidad KDE, y las aplicaciones que se crean con para él.
Hay que recordar que los desarrolladores de KDE decidieron lanzar actualizaciones mensuales de este proyecto y lo están cumpliendo con puntualmente. La idea es ofrecer pocas pero consolidadas novedades, a la vez que se mantiene el proyecto evolucionando y siempre adaptándose al vertiginoso mundo del Software Libre.
Una gran noticia para la Comunidad KDE que demuestra la evolución continua del proyecto que continua ganando prestigio en el mundo de los entornos de trabajo Libres.
Más información: KDE
¿Qué es KDE Frameworks?
Para los que no lo sepan, KDE Frameworks añade más de 70 librerías a Qt que proporcionan una gran variedad de funcionalidades necesarias y comunes, precisadas por los desarrolladores, testeadas por aplicaciones específicas y publicadas bajo licencias flexibles. Como he comentado, este entorno de programación es la base para el desarrollo tanto de las nuevas aplicaciones KDE y del escritorio Plasma 5.

Aquí podéis encontrar un listado con todos estos frameworks y la serie de artículos que dedico a KDE Frameworks en el blog,
Recuerda que puedes ver una introducción a Frameworks 5.0 en su anuncio de lanzamiento.
#DuckDuckGo dona 750.000$ a diversas organizaciones
El buscador de internet DuckDuckGo dona 750.000$ a diversas organizaciones que defienden la privacidad en internet y otros derechos civiles

En internet, no solo se pueden realizar búsquedas con la gran G, también existen otros buscadores, entre ellos DuckDuckGo, que tiene como premisa respetar la privacidad de los usuarios.
De manera anual, la empresa detrás de DuckDuckGo, realiza unos donativos a diversas organizaciones y asociaciones. Esta vez, por décimo año, ha vuelto a donar dinero, esta vez llegando a la cantidad de 750.000$ que ha repartido entre varias organizaciones.
En estos 10 años de donaciones, el total de dinero repartido llega hasta más de 2.5 millones de dólares. Pero echemos un vistazo al dinero que ha repartido este año 2020 y a quien se lo ha donado.
- 200.000$ para Center for Information Technology Policy (CITP)
- 150.000$ para Electronic Frontier Foundation (EFF)
- 50.000$ para European Digital Rights (EDRi)
- 50.000$ para Public Knowledge
- 50.000$ para The Markup
- 25.000$ para Algorithmic Justice League
- 25.000$ para Bits of Freedom
- 25.000$ para Center for Critical Internet Inquiry (C2i2)
- 25.000$ para Electronic Frontiers Australia (EFA)
- 25.000$ para Competition Law Forum
- 25.000$ para Freiheitsrechte (GFF)
- 25.000$ para Open Rights Group
- 25.000$ para Restore The Fourth
- 25.000$ para TechFreedom
- 25.000$ para Tor Project
Organizaciones de diferentes países y continentes que de una u otra forma defienden luchan o protegen la libertad de expresión, la privacidad y otros derechos civiles básicos para vivir en una sociedad democrática sana. Y que son derechos que lamentablemente hay que seguir reclamando y exigiendo como propios, ya que se ven amenazados por corporaciones o gobiernos.

The benefits of making code worse
A recent twitter discussion reminded me of an interesting XTC discussion last year. The discussion topic was refactoring code to make it worse. We discussed why this happens, and what we can do about it.
I found the most interesting discussion arose from the question “when might this be a good thing?”—when is it beneficial to make code worse?
Refactorings are small, safe, behaviour-preserving transformations to code. Refactoring is a technique to improve the design of existing code without changing the behaviour. The refactoring transformations are merely a tool. The result may be either better or worse.
Make it worse for you; make it better for someone else
Refactoring ruthlessly can keep code habitable, inline with our best understanding of the domain, even aesthetically pleasing.
They can also make the code worse. Whether the result is better or worse is in the eye of the beholder. What’s better to one person may be worse to another. What’s better for one team may be worse for another team.
For example, some teams may be more comfortable with abstraction than others. Some teams prefer code that more explicitly states how it is working at a glance. Some people may be comfortable with OO design patterns and find functional programming idioms unfamiliar, and vice versa.
You may refactor the code to a state you’re less happy with but the team as a whole prefers.
Refactoring the code through different forms also allows for conversations to align on a preferred style in a team. After a while you can often start to predict what others on the team are going to think of a given refactoring even without asking them.
Making refactoring a habit, e.g. as part of the TDD cycle accelerates this, as do mechanisms for fast feedback between each person in the team—such as pairing with rotation or collective group code review.
Learning through Exploration
Changing the structure of code without changing its behaviour can help to understand what the code’s doing, why it’s written in that way, how it fits into the rest of the system.
In his book “Working effectively with legacy code” Michael feathers calls this “Scratch Refactoring”. Refactor the code without worrying about whether your changes are safe, or even better.
Then throw those refactorings away.
Exploratory refactoring can be done even when there’s no tests, even when you don’t have enough understanding of the system to know if your change is better or worse, even when you don’t know the acceptance criteria for the system.
Moulding the code into different forms that have the same behaviour can increase your understanding of what that core behaviour is.
A sign it’s safe to take risks
If every refactoring you perform makes the code better, it seems likely that we could be more courageous in our refactoring attempts.
If we only tackle the changes where we know what better looks like and leave scary code alone the system won’t stay simple.
If we’re attempting to improve code we don’t fully understand and don’t intuitively know the right design for we’ll get it wrong some of the time.
It’s easy to try so hard to avoid the risk of bad things happening that we also get in the way of good things happening.
Many teams use gating code review before code may make its way to production. Establishing a gate to stop bad code making it into production, that also slows down good code getting to production.
Refactorings are often small steps towards a deeper insight into the domain of the code we’re working on. Sometimes those steps will be in a useful direction, sometimes wrong. All of them will build up understanding in the team. Not all of them will be unquestionably better at each integration point, and could easily be filtered out by a risk-averse code review gate. Avoiding the risk that a refactoring might be taking us in the wrong path may rob us of the chance of a breakthrough in the next refactoring, or the one after.
A team that’s not afraid to make improvements to the system will also get it wrong some of the time. That has to be ok. We learn as much or more from the failures.
Making it safe to make code worse
Extreme programming practices really help create an environment where it’s safe experiment with code in this manner.
Pair programming means you’ve got a second person to catch some of the riskiest things that could happen and give immediate feedback in the moment. It gives two perspectives on the shape the code should be in. Tom Johnson calls this optician-style “Do you prefer this… or this”. Refactorings are small changes so it’s feasible to switch back and forth between each structure to compare and consider together.
Group code review. (Reviewing code together as a team, after it’s already in production) can build a shared understanding of what the team considers good code. Help you foresee the preferences of the rest of your team. Between you build a better understanding of the code than you could even in a pair. Spot the refactoring paths we’ve embarked on that have made code worse rather than better. Highlight changes to make the next time we’re in the area.
Continuous integration means we’re only making small steps before getting feedback from integrating the code. The size of our mistakes is limited.
Test Driven Development gives us a safety net that tells us when our refactoring may have not just changed the structure of the code but also inadvertently the behaviour. i.e. it wasn’t a refactoring. Test suites going red during a refactoring is a “surprise” we can learn from. We predict the suite will stay green. If it goes red then there’s something we didn’t fully understand about the code. Surprises are where learning happens.
Test Driven Development also makes refactoring habitual. Every micro-iteration of behaviour we perform to the system includes refactoring. Tidying the implementation, trying out another approach, simplifying the test, improving its diagnostic power (maybe not strictly a refactoring). If you never move onto writing the next test without doing at least some refactoring you’ll build up the habit and skill at refactoring fast. If you do lots of refactorings some of them will make things worse, and that’s ok.
The post The benefits of making code worse appeared first on Benji's Blog.
