unwrite if statements with switch and case, php gilded rose
one text
https://github.com/emilybache/GildedRose-Refactoring-Kata/tree/main/php
im doing the gilded rose refactoring kata for php right now. I have written some unittests and they all work with the standard GildedRose.php code. Now i wanted to refactory the 40 line of if statements to do the code easier to read, but somewhere a mistake has crept in and idk where and how.
my unittest are like (for each item):
public function testAgedBrieAtBeginning(): void // +1 quality till sell_in = 0 than +2 quality
{
$items = [new Item('Aged Brie', 2, 0)];
$gildedRose = new GildedRose($items);
$gildedRose->updateQuality();
$this->assertEquals($items[0]->sell_in, 1);
$this->assertEquals($items[0]->quality, 1);
}
public function testAgedBrieWhenSellInZero(): void
{
$items = [new Item('Aged Brie', 0, 2)];
$gildedRose = new GildedRose($items);
$gildedRose->updateQuality();
$this->assertEquals($items[0]->sell_in, -1);
$this->assertEquals($items[0]->quality, 4);
}
public function testAgedBrieDontIncreaseMaximum(): void // stand at 50 quality
{
$items = [new Item('Aged Brie', -28, 50)];
$gildedRose = new GildedRose($items);
$gildedRose->updateQuality();
$this->assertEquals($items[0]->sell_in, -29);
$this->assertEquals($items[0]->quality, 50);
}
and my GildedRose.php is:
<?php
declare(strict_types=1);
namespace GildedRose;
final class GildedRose
{
/**
* @var Item[]
*/
private $items;
public function __construct(array $items)
{
$this->items = $items;
}
public function updateQuality(): void
{
switch ($this->items) {
case 'Normal':
$this->tickNormal();
return;
case 'Aged Brie':
$this->tickAgedBrie();
return;
case 'Sulfaras, Hand of Ragnaros':
$this->tickSulfuras();
return;
case 'Backstage passes to a TAFKAL80ETC concert':
$this->tickBackstage();
return;
}
}
private function tickNormal(): void // for Dexterity, Elixir & Conjured
{
$this->sell_in--;
if($this->quality == 0) {
return;
}
$this->quality--;
if ($this->sell_in <= 0) {
$this->quality--;
}
}
private function tickAgedBrie()
{
$this->sell_in -= 1;
if($this->quality >= 50) {
return;
}
$this->quality += 1;
if ($this->sell_in <= 0) {
$this->quality += 1;
}
}
private function tickSulfuras() : void
{
}
private function tickBackstage() : void
{
$this->sell_in -= 1;
if ($this->quality >= 50) {
return;
}
if ($this->sell_in < 0) {
$this->quality = 0;
return;
}
$this->quality += 1;
if ($this->sell_in < 10) {
$this->quality += 1;
}
if ($this->sell_in < 5) {
$this->quality += 1;
}
}
}
Firstly: The code was a full chaos. Look at the github repository /src/GildedRose.php. I have write some unittest to the original code to save the program. my unittest looks all similar to above. I test the changes of every items as they should be (https://github.com/emilybache/GildedRose-Refactor). After the unittests, i started to change the GildedRose.php to uncode the if-statements..
Source