mirror of
https://github.com/emilybache/GildedRose-Refactoring-Kata.git
synced 2026-05-15 14:21:12 +00:00
test: add characterization tests as safety net
This commit is contained in:
parent
229dc61b8b
commit
3219d73d3e
86
README.md
86
README.md
@ -1,55 +1,71 @@
|
||||
_Support this and all my katas via [Patreon](https://www.patreon.com/EmilyBache)_
|
||||
|
||||
# Gilded Rose Refactoring Kata
|
||||
|
||||
You can find out more about this exercise in my YouTube video [Why Developers LOVE The Gilded Rose Kata](https://youtu.be/Mt4XpGxigT4). I also have a video of a worked solution in Java - [Gilded Rose Kata, Hands-on](https://youtu.be/OdnV8hc9L7I)
|
||||
## Análisis Inicial de Requisitos: Gilded Rose1.
|
||||
|
||||
I use this kata as part of my work as a technical coach. I wrote a lot about the coaching method I use in this book [Technical Agile Coaching with the Samman method](https://leanpub.com/techagilecoach). A while back I wrote this article ["Writing Good Tests for the Gilded Rose Kata"](http://coding-is-like-cooking.info/2013/03/writing-good-tests-for-the-gilded-rose-kata/) about how you could use this kata in a [coding dojo](https://leanpub.com/codingdojohandbook).
|
||||
### 1. ¿Cuántos tipos de ítems diferentes se mencionan y cuál es su comportamiento?
|
||||
Se mencionan 5 tipos de artículos con comportamientos específicos:
|
||||
- **Items Normales:** La calidad disminuye en 1 cada día. Si la fecha de venta ha pasado (SellIn < 0), disminuye en 2.
|
||||
- **Aged Brie (Queso Brie envejecido):** La calidad aumenta en 1 cada día. Si la fecha de venta ha pasado, la calidad aumenta en 2.
|
||||
- **Sulfuras (Artículo legendario):** No tiene fecha de venta y su calidad es siempre 80. No sufre cambios.
|
||||
- **Backstage passes (Entradas al Backstage):** Su calidad aumenta según la cercanía del concierto:
|
||||
- Más de 10 días: +1 de calidad.
|
||||
- 10 días o menos: +2 de calidad.
|
||||
- 5 días o menos: +3 de calidad.
|
||||
- **Después del concierto (SellIn < 0):** La calidad cae a 0.
|
||||
- **Conjured (Artículos conjurados):** Degradan su calidad el doble de rápido que los artículos normales (este es el ítem a implementar).
|
||||
|
||||
|
||||
## How to use this Kata
|
||||
### 2. ¿Qué significan SellIn y Quality y cuáles son sus límites?
|
||||
- **SellIn:** Indica la cantidad de días que faltan para la fecha recomendada de venta del artículo. No tiene un límite superior o inferior definido, pero afecta el ritmo de cambio de la calidad cuando llega a 0.
|
||||
- **Quality:** Indica cuán valioso es el artículo.
|
||||
- *Límite inferior:* Nunca puede ser menor a 0.
|
||||
- *Límite superior:* No puede superar 50 (excepto para Sulfuras, que es fijo en 80).
|
||||
|
||||
### 3. ¿Cuál es la restricción más importante sobre la clase Item?
|
||||
La restricción crítica es que no se debe modificar la clase Item ni sus propiedades. Esta clase pertenece a un tercero (el "duende") y el sistema debe interactuar con ella tal como está, limitando los cambios únicamente a la clase GildedRose o extensiones del código.
|
||||
|
||||
The simplest way is to just clone the code and start hacking away improving the design. You'll want to look at the ["Gilded Rose Requirements"](https://github.com/emilybache/GildedRose-Refactoring-Kata/blob/main/GildedRoseRequirements.md) which explains what the code is for. I strongly advise you that you'll also need some tests if you want to make sure you don't break the code while you refactor.
|
||||
### 4. ¿Qué nuevo ítem hay que implementar al final del kata?
|
||||
Se debe implementar el ítem "Conjured" (Conjurados), cuya característica principal es que su calidad se degrada el doble de rápido que la de un objeto normal.
|
||||
|
||||
You could write some unit tests yourself, using the requirements to identify suitable test cases. I've provided a failing unit test in a popular test framework as a starting point for most languages.
|
||||
|
||||
Alternatively, use the Approval tests provided in this repository. (Read more about that in the section "Text-based Approval Testing").
|
||||
## Ficha de Análisis de Código Legacy: Gilded Rose
|
||||
### 1. OLORES DE CÓDIGO (Code Smells) detectados:
|
||||
|
||||
The idea of the exercise is to do some deliberate practice, and improve your skills at designing test cases and refactoring. The idea is not to re-write the code from scratch, but rather to practice taking small steps, running the tests often, and incrementally improving the design.
|
||||
**[X] Método demasiado largo:** El método update_quality tiene aproximadamente 38 líneas de pura lógica densa sin separaciones claras.
|
||||
|
||||
### Gilded Rose Requirements in other languages
|
||||
|
||||
- [English](GildedRoseRequirements.md)
|
||||
- [Español](GildedRoseRequirements_es.md)
|
||||
- [Français](GildedRoseRequirements_fr.md)
|
||||
- [Italiano](GildedRoseRequirements_it.md)
|
||||
- [日本語](GildedRoseRequirements_jp.md)
|
||||
- [Português](GildedRoseRequirements_pt-BR.md)
|
||||
- [Русский](GildedRoseRequirements_ru.md)
|
||||
- [Українська](GildedRoseRequirements_ua.md)
|
||||
- [ไทย](GildedRoseRequirements_th.md)
|
||||
- [中文](GildedRoseRequirements_zh.txt)
|
||||
- [한국어](GildedRoseRequirements_kr.md)
|
||||
- [German](GildedRoseRequirements_de.md)
|
||||
- [Euskara](GildedRoseRequirements_eu.md)
|
||||
- [Galego](GildedRoseRequirements_gl.md)
|
||||
**[X] Condicionales anidados:** Hay secciones con hasta 4 o 5 niveles de profundidad (por ejemplo, los if dentro del bloque de Backstage passes).
|
||||
|
||||
## Text-Based Approval Testing
|
||||
|
||||
Most language versions of this code have a [TextTest](https://texttest.org) fixture for Approval testing. For information about this, see the [TextTests README](https://github.com/emilybache/GildedRose-Refactoring-Kata/tree/main/texttests)
|
||||
**[X] Números mágicos:** Se usan literales como 11, 6, 50 y 0 directamente en la lógica sin explicar qué representan (como "Límite de calidad máxima" o "Umbral de urgencia").
|
||||
|
||||
## History of the exercise
|
||||
|
||||
This Kata was originally created by Terry Hughes (http://twitter.com/TerryHughes). It is already on GitHub [here](https://github.com/NotMyself/GildedRose). Bobby Johnson described the kata in an article titled "Refactor This: The Gilded Rose Kata", but unfortunately it is no longer on the internet. I found it on the Wayback Machine [here](https://web.archive.org/web/20240525015111/https://iamnotmyself.com/refactor-this-the-gilded-rose-kata/).
|
||||
**[X] Strings literales repetidos:** Los nombres "Aged Brie", "Sulfuras, Hand of Ragnaros" y "Backstage passes to a TAFKAL80ETC concert" aparecen múltiples veces escritos a mano, lo que facilita errores de dedo.
|
||||
|
||||
I translated the original C# into a few other languages, (with a little help from my friends!), and slightly changed the starting position. This means I've actually done a small amount of refactoring already compared with the original form of the kata, and made it easier to get going with writing tests by giving you one failing unit test to start with. I also added test fixtures for Text-Based approval testing with TextTest (see [the TextTests](https://github.com/emilybache/GildedRose-Refactoring-Kata/tree/main/texttests))
|
||||
|
||||
As Bobby Johnson points out in his article "Why Most Solutions to Gilded Rose Miss The Bigger Picture" (on the Wayback Machine [here](https://web.archive.org/web/20230530152324/https://iamnotmyself.com/why-most-solutions-to-gilded-rose-miss-the-bigger-picture/)), it'll actually give you
|
||||
better practice at handling a legacy code situation if you do this Kata in the original C#. However, I think this kata
|
||||
is also really useful for practicing writing good tests using different frameworks and approaches, and the small changes I've made help with that. I think it's also interesting to compare what the refactored code and tests look like in different programming languages.
|
||||
**[X] Falta de abstracción:** Toda la lógica de negocio para cada tipo de ítem diferente está mezclada en un solo bucle for, en lugar de estar delegada a clases o métodos específicos.
|
||||
|
||||
## Contributing
|
||||
**[ ] Variables con nombres poco descriptivos:** Aunque item, quality y sell_in son claros, la estructura lógica hace que sea difícil seguir qué está pasando.
|
||||
|
||||
I have been struggling for some time with the maintenance burden for the Gilded Rose respository. I get frequent spurious pull requests from people who have been assigned to work on it as an exercise by some other organization (I don't know who) and mistakenly send me a pull request with their solution. I get so many of these it's a significant amount of work to check that they aren't a legitimate contribution. It's really annoying. I have sadly now added a restriction now so that only prior contributors can now open issues, comment, or create pull requests.
|
||||
**Otros:**
|
||||
- **Lógica Negada:** El uso constante de if item.name != ... hace que el código sea mucho más difícil de leer que si fuera positivo.
|
||||
|
||||
If you would like to make an actual contribution that improves the starting position of the exercise, please see [CONTRIBUTING.md](./CONTRIBUTING.md) for some ideas about how to get involved.
|
||||
- **Código Muerto/Redundante:** La expresión item.quality = item.quality - item.quality es una forma muy extraña de decir item.quality = 0.
|
||||
|
||||
|
||||
### 2. PUNTOS DE CAMBIO (Dónde añadir "Conjured"):
|
||||
Tendría que ser dentro del for item in self.items:, probablemente cerca de la línea 10 o al final del método tras evaluar si sell_in < 0. El riesgo de modificar ahí es debido a la alta anidación y las negaciones (!=), añadir un nuevo if puede romper accidentalmente la lógica de otros ítems o hacer que un ítem sea procesado por dos bloques distintos, duplicando la degradación de su calidad.
|
||||
|
||||
### 3. DEPENDENCIAS:
|
||||
- **¿Qué clases/structs usa GildedRose?**
|
||||
Depende totalmente de la clase Item.
|
||||
|
||||
- **¿Quién llama a update_quality()?**
|
||||
En el contexto del código proporcionado, no se ve el llamador, pero el sistema indica que se ejecuta "al final de cada día" para actualizar el inventario.
|
||||
|
||||
### 4. PREGUNTAS SIN RESPUESTA en el código:
|
||||
- **¿Qué pasa si quality es negativa al entrar?**
|
||||
El código actual solo resta calidad si item.quality > 0. Si entra un valor como -5, se quedaría en -5 (aunque los requisitos dicen que nunca debe ser negativa).
|
||||
|
||||
- **¿Qué pasa con un nombre de ítem desconocido?**
|
||||
El código lo trata como un "Ítem Normal" por defecto debido a las estructuras if item.name != ....
|
||||
6
python/package-lock.json
generated
Normal file
6
python/package-lock.json
generated
Normal file
@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "python",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {}
|
||||
}
|
||||
Loading…
Reference in New Issue
Block a user