Skip to content

Instantly share code, notes, and snippets.

@mike-rogers
Created November 10, 2015 19:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mike-rogers/88dca559deecdc6adaa0 to your computer and use it in GitHub Desktop.
Save mike-rogers/88dca559deecdc6adaa0 to your computer and use it in GitHub Desktop.
Gilded Rose Kata in Scala
package com.gildedrose
case class AgedBrie(var sellWithin: Int, var value: Int)
extends Item("Aged Brie", sellWithin, value)
case class BackstagePass(var sellWithin: Int, var value: Int)
extends Item("Backstage passes to a TAFKAL80ETC concert", sellWithin, value)
case class Sulfuras(var sellWithin: Int, var value: Int)
extends Item("Sulfuras, Hand of Ragnaros", sellWithin, value)
object Services {
val sellInUpdater = new DefaultSellInUpdater
val qualityUpdater = new DefaultQualityUpdater
}
class GildedRose(val items: Array[Item]) {
import Services._
def updateQuality() = items.foreach {
case item@AgedBrie(_, _) => new GildedRoseUpdater()(sellInUpdater, new IncrementingQualityUpdater()).update(item)
case item@BackstagePass(_, _) => new GildedRoseUpdater()(sellInUpdater, new BackstagePassQualityUpdater()).update(item)
case Sulfuras(_, _) =>
case item => new GildedRoseUpdater()(sellInUpdater, qualityUpdater).update(item)
}
}
trait QualityUpdater {
def apply(item: Item)
}
class DefaultQualityUpdater extends QualityUpdater {
def apply(item: Item): Unit = {
item.quality = item.quality - (if (item.sellIn >= 0) 1 else 2)
item.quality = Math.max(item.quality, 0)
}
}
class IncrementingQualityUpdater extends QualityUpdater {
def apply(item: Item): Unit = {
item.quality = Math.min(item.quality + 1, 50)
}
}
class BackstagePassQualityUpdater extends QualityUpdater {
def apply(item: Item): Unit = {
item.quality = item.quality + (
if (item.sellIn > 10) 1
else if (item.sellIn > 5) 2
else if (item.sellIn > 0) 3
else -item.quality
)
}
}
trait SellInUpdater {
def apply(item: Item)
}
class DefaultSellInUpdater extends SellInUpdater {
def apply(item: Item): Unit = {
item.sellIn = item.sellIn - 1
}
}
class GildedRoseUpdater (
implicit val sellInUpdater: SellInUpdater,
implicit val qualityUpdater: QualityUpdater) {
def update(item: Item): Unit = {
sellInUpdater(item)
qualityUpdater(item)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment