Skip to content

kndl/DevelopDenverTalk

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Immutability: A Tool for Suckers

####(And other such blanket statements)

##TODO:

  • Make examples more concrete
  • Stick with a single example throughout the talk
  • General unifying story
  • Does append/prepend bring any value
  • Run code examples back to back
  • Where (specifically) does the constant come from?
  • Make sure to codify the example of "immutability done mutably" or get rid of it
  • Cut out snippets of code which are important to talk about

###Example 1:

This is an example of concurrency gone very wrong. Notice that multiple threads are mutating shared memory without any form of synchronization. This leads to non-deterministic and non-sensical behavior. Purely a motivating example as to the benefits of immutability

###Example 2:

This is an example of using an immutable data structure to accumulate a series of results. Notice the following method definition

def buildABigListRecursivly(size: Int): Seq[Int] = {

  // Inner loop function. For those familiar with Scala, this will be
  // familiar. For other, this finction works just like any other
  // function defined in out class/object, but is only visible inside
  // "buildABigListRecursivly"
  @tailrec
  def loop(acc: Seq[Int] = Seq.empty[Int]): Seq[Int] = {
    if (size == acc.size) acc
    else {
      loop(acc.size +: acc)
    }
  }
  loop()
}

the call to loop(acc.size +: acc) is a right associative operator which prepends to the accumulator list acc. Something to note about this implementation:

  • Does it matter that we are prepending vs. appending to acc?
  • Is this accumulator ever visible outside of the thread?
  • Is is subject to concurrent modification?

###Example 3:

This is a subtly modified version of Example 2. Notice the new definition of the inner loop method:

@tailrec
def loop(acc: ListBuffer[Int] = ListBuffer.empty[Int]): ListBuffer[Int] = {
 if (size == acc.size) acc
 else {
   acc.append(acc.size)
   loop(acc)
 }
}

Instead of prepending to a list and accumulating with an immutable data-structure, we are appending to a mutable structure and passing that up the call stack. Things to think about:

  • What is the difference between a ListBuffer and the default Seq?
  • Are we subject to concurrent modification?

About

Talk examples and docs for my talk at Develop Denver 2015

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • Scala 100.0%