Immutable Object is Useful

github logo ・1 min read

From some talk videos I watched this style of code, Let's start with a simple example:

class Fish
  def initialize(age)
    @age = age
  end

  def say()
    "My age is #{@age}"
  end
end

fish = Fish.new(3)
fish.say() #=> My age is 3

This is called immutable or functional object. It's solid and cannot be broken after created.

Then how to change the age in sample?

class Fish
  #added
  def with_age(age)
    Fish.new(age)
  end
end

fish.with_age(5).say() #=>My age is 5

This code style is fun and useful. It'll reduce the change of object.

What's your idea?

twitter logo DISCUSS
Classic DEV Post from Dec 22 '18

How does your workplace approach recognition?

Does your workplace have a strategy for recognising team members?

chenge profile image
Ruby, and learn Rust, Go, Elixir, Erlang...

Need a change?

dev.to now has dark mode.

Go to the "misc" section of your settings and select night theme ❤️