Learning From Other Languages - Immutability

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...

D79fc498d7a5b2ce12180890247476f0?s=128

Jon Rowe

March 13, 2018
Tweet

Transcript

  1. 2.
  2. 3.
  3. 4.
  4. 5.

    Immutability In object-oriented and functional programming, an immutable object is

    an object whose state cannot be modified after it is created.
  5. 6.

    Mutability This is in contrast to a mutable object, which

    can be modified after it is created.
  6. 10.
  7. 12.

    Side effects? In medicine, a side effect is an effect,

    whether therapeutic or adverse, that is secondary to the one intended;
  8. 13.

    Side effects? In computer science a side effect is when

    a function or expression modifies some state outside its scope.
  9. 16.

    Side effects? heros = {turtle: "Michaelenglo"} def mutate(hash) hash[:turtle] =

    "Rafael" end mutate heros # => "Rafael" heros # => {:turtle=>"Rafael"}
  10. 18.
  11. 24.

    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>
  12. 26.

    Immutability in Ruby 6 += 2 # SyntaxError: (irb):9: syntax

    error, # unexpected tOP_ASGN, expecting end-of-input
  13. 27.

    Immutability in Ruby → Frozen objects → Primitives such as

    numbers and symbols → String literals from Ruby 2.3, optionally
  14. 29.

    Frozen string # frozen_string_literal: true "Hello".upcase! `upcase!': can't modify frozen

    String (RuntimeError) x = String.new('Hello') x.upcase! puts x #=> 'HELLO'
  15. 30.

    Immutability in Ruby → Libararies such as: → ice_nine (deep

    freezing objects) → values immutable structs → immutable-ruby immutable enumerables
  16. 32.

    Conclusion - Benefits → Immutability helps with thread safety →

    Immutability can save memory usage → Immutability has the potential for cleaner, side effect free code.
  17. 33.

    Conclusion - Drawbacks → In some cases mutability is more

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