Sunday, December 30, 2007

Coolest Code I've Ever Written

Because Scala lets you name methods pretty much whatever you want, I got the chain wires together like this:



@Test
def lastPowerSourceInChainShouldBeNotifiedWhenFirstInChainIsTurnedOff() = {
//given
val first = new Generator
val secondToLast = new Wire

first-->new Wire-->new Wire-->new Wire-->secondToLast

val last = createMockWithConnectionTo(secondToLast)

// when
first.turnOff

// then
verify(Array(last))
}

private def createMockWithConnectionTo( p: PowerSource ): PowerSource = {
val mockPowerSource: PowerSource = createStrictMock(classOf[PowerSource]).asInstanceOf[PowerSource];
expect( mockPowerSource <-- p ).andReturn( p ) expect( mockPowerSource.handleStateChanged( p ) ) replay(Array(mockPowerSource)) p --> mockPowerSource
mockPowerSource
}


The -->'s are actually methods on any PowerSource that connects the two together. So, the code can actually look like a chain of wires connected together. This is totally the coolest thing ever.

1 comment: