Kotlin 75.5 - Foreshadowing
Articles #76 and #77 are a long, tiny-step refactoring. Here, we’ll preview where we started and where we wind up. Use this as an enticement to see how it was done, or as an opportunity to skim the articles, or a chance to do something else entirely.
Starting Code
The method we start with is this:
private fun updateItem(item: Item) {
if (item.name != "Aged Brie" && item.name != "Backstage passes to a TAFKAL80ETC concert") {
if (item.quality > 0) {
if (item.name != "Sulfuras, Hand of Ragnaros") {
item.quality = item.quality - 1
}
}
} else {
if (item.quality < 50) {
item.quality = item.quality + 1
if (item.name == "Backstage passes to a TAFKAL80ETC concert") {
if (item.sellIn < 11) {
if (item.quality < 50) {
item.quality = item.quality + 1
}
}
if (item.sellIn < 6) {
if (item.quality < 50) {
item.quality = item.quality + 1
}
}
}
}
}
if (item.name != "Sulfuras, Hand of Ragnaros") {
item.sellIn = item.sellIn - 1
}
if (item.sellIn < 0) {
if (item.name != "Aged Brie") {
if (item.name != "Backstage passes to a TAFKAL80ETC concert") {
if (item.quality > 0) {
if (item.name != "Sulfuras, Hand of Ragnaros") {
item.quality = item.quality - 1
}
}
} else {
item.quality = item.quality - item.quality
}
} else {
if (item.quality < 50) {
item.quality = item.quality + 1
}
}
}
}
Ending Code
At the end of #77, we have this. Not perfect but really rather surprisingly nice.
private fun updateItem(item: Item) {
when (item.name) {
PROD_SULF -> { /*nothing*/ }
PROD_BRIE -> { updateBrie(item) }
PROD_PASS -> { updatePasses(item) }
else -> { updateNormal(item) }
}
}
private fun updateBrie(item: Item) {
increaseQualityUpTo50(item)
item.sellIn = item.sellIn - 1
if (item.sellIn < 0) {
increaseQualityUpTo50(item)
}
}
private fun updatePasses(item: Item) {
increaseQualityUpTo50(item)
if (item.sellIn < 11) {
increaseQualityUpTo50(item)
}
if (item.sellIn < 6) {
increaseQualityUpTo50(item)
}
item.sellIn = item.sellIn - 1
if (item.sellIn < 0) {
item.quality = 0
}
}
private fun updateNormal(item: Item) {
decrementQualityTowardZero(item)
item.sellIn = item.sellIn - 1
if (item.sellIn < 0) {
decrementQualityTowardZero(item)
}
}
private fun decrementQualityTowardZero(item: Item) {
if (item.quality > 0) {
item.quality = item.quality - 1
}
}
private fun increaseQualityUpTo50(item: Item) {
if (item.quality < 50) {
item.quality = item.quality + 1
}
}
So …
I hope you’ll follow along in #76 and #77, at least enough to discover that this improvement was done with simple local changes, almost all of them automated. Very little deep thinking required, darn good thing, too, because deep thinking is error-prone here at my house.
See you soon!