DEV Community

chenge
chenge

Posted on

Immutable Object is Useful

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?

Top comments (0)