Last active
August 29, 2015 14:02
-
-
Save dsugden/c6a8f48ed975089f73f2 to your computer and use it in GitHub Desktop.
A traditional OO mutation code example showing methods that hide side effects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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