Learning From Other Languages - Immutability

Jon Rowe
March 13, 2018

Learning From Other Languages - Immutability

So many talks are about learning new languages and technology, but what can we bring back from those into Ruby...

Jon Rowe

March 13, 2018

Annual Pro sale · Save $30

Have presentations of your own?

Share with private links, password protection, and more control over your work.

Transcript

34 slides
  1. Immutability In object-oriented and functional programming, an immutable object is

    an object whose state cannot be modified after it is created.
  2. Mutability This is in contrast to a mutable object, which

    can be modified after it is created.
  3. Side effects? In medicine, a side effect is an effect,

    whether therapeutic or adverse, that is secondary to the one intended;
  4. Side effects? In computer science a side effect is when

    a function or expression modifies some state outside its scope.
  5. Side effects? heros = {turtle: "Michaelenglo"} def mutate(hash) hash[:turtle] =

    "Rafael" end mutate heros # => "Rafael" heros # => {:turtle=>"Rafael"}
  6. Immutability in Ruby mutate("my_string".freeze) # => RuntimeError: can't modify frozen

    String {a: :hash}.freeze # => RuntimeError: can't modify frozen Hash any_object.freeze # => RuntimeError: can't modify frozen <Object>
  7. Immutability in Ruby 6 += 2 # SyntaxError: (irb):9: syntax

    error, # unexpected tOP_ASGN, expecting end-of-input
  8. Immutability in Ruby → Frozen objects → Primitives such as

    numbers and symbols → String literals from Ruby 2.3, optionally
  9. Frozen string # frozen_string_literal: true "Hello".upcase! `upcase!': can't modify frozen

    String (RuntimeError) x = String.new('Hello') x.upcase! puts x #=> 'HELLO'
  10. Immutability in Ruby → Libararies such as: → ice_nine (deep

    freezing objects) → values immutable structs → immutable-ruby immutable enumerables
  11. Conclusion - Benefits → Immutability helps with thread safety →

    Immutability can save memory usage → Immutability has the potential for cleaner, side effect free code.
  12. Conclusion - Drawbacks → In some cases mutability is more

    performant (e.g. RSpec mutates strings to avoid allocations)

More Decks by Jon Rowe

Other Decks in Technology