Skip to content

Instantly share code, notes, and snippets.

@dsugden
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsugden/c6a8f48ed975089f73f2 to your computer and use it in GitHub Desktop.
Save dsugden/c6a8f48ed975089f73f2 to your computer and use it in GitHub Desktop.
A traditional OO mutation code example showing methods that hide side effects
class TraditionalMutation{
var total : List[Int] = Nil // Mutable List
/*
Add i to total, return it's sum
This method hides the effect of updating total
*/
def sum(i:Int):Int = {
total = i :: total // SIDE EFFECT
if(total.length > 1) 99 else total.sum // this is ancontrived bug based on internal state
}
}
object TraditionalTest {
val traditional = new TraditionalMutation
// The type of this function is Int => Int, but it should be (Int,TraditionalMutation) => (Int,TraditionalMutation)
val one = traditional.sum(1)
// I haven't explicitly tracked the fact that traditional.total has changed
val two = traditional.sum(2)
// nothing tells me that traditional.total is different, I just better know "in my head"
// I have to worry about how traditional evolves over time
val three = traditional.sum(3)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment