So many talks are about learning new languages and technology, but what can we bring back from those into Ruby...
Learning from other languagesImmutability
View Slide
ImmutabilityIn object-oriented and functional programming,an immutable object is an object whose state cannotbe modified after it is created.
MutabilityThis is in contrast to a mutable object, which can bemodified after it is created.
Why isimmutabilitygood?
Why is immutability good?→ Inherently thread safe
Why is immutability good?→ Inherently thread safe→ More memory efficient
Why is immutability good?→ Inherently thread safe→ More memory efficient→ No side effects
Side effects?
Side effects?In medicine, a side effect is an effect, whethertherapeutic or adverse, that is secondary to the oneintended;
Side effects?In computer science a side effect is when a functionor expression modifies some state outside its scope.
Side effects?a = "string"def some_method(takes_a_string)takes_a_string.upcase!endsome_method(a)
Side effects?a = "string"def some_method(takes_a_string)takes_a_string.upcase!endsome_method(a)puts a# => "STRING"
Side effects?heros = {turtle: "Michaelenglo"}def mutate(hash)hash[:turtle] = "Rafael"endmutate heros# => "Rafael"heros# => {:turtle=>"Rafael"}
Side effects?my.contacts << Person.new# => [#, #]
Immutability in other languagesElixir - everything is immutable.
Immutability in other languagesAda, C#, C++, Java, Perl, Python, JavaScript, Racket,Scala
Immutabilityin Ruby
Immutability in Ruby→ Frozen objects
Immutability in Ruby"my_string".freeze{a: :hash}.freezeany_object.freeze
Immutability in Rubymutate("my_string".freeze)# => RuntimeError: can't modify frozen String{a: :hash}.freeze# => RuntimeError: can't modify frozen Hashany_object.freeze# => RuntimeError: can't modify frozen
Immutability in Ruby→ Frozen objects→ Primitives such as numbers and symbols
Immutability in Ruby6 += 2# SyntaxError: (irb):9: syntax error,# unexpected tOP_ASGN, expecting end-of-input
Immutability in Ruby→ Frozen objects→ Primitives such as numbers and symbols→ String literals from Ruby 2.3, optionally
Frozen stringruby --enable-frozen-string-literal# frozen_string_literal: true
Frozen string# frozen_string_literal: true"Hello".upcase!`upcase!': can't modify frozen String (RuntimeError)x = String.new('Hello')x.upcase!puts x #=> 'HELLO'
Immutability in Ruby→ Libararies such as:→ ice_nine (deep freezing objects)→ values immutable structs→ immutable-ruby immutable enumerables
Conclusion
Conclusion - Benefits→ Immutability helps with thread safety→ Immutability can save memory usage→ Immutability has the potential for cleaner, sideeffect free code.
Conclusion - Drawbacks→ In some cases mutability is more performant (e.g.RSpec mutates strings to avoid allocations)
Thanks@jonrowe