Let's say you have the code something like this
def something_else 2 end def do_something x = 1 x += 2 if something_else.even? puts "#{x} is bla bla" # use x for some other operation end
If you observe the above code, in the do_something
method. We are mutating the variable x based on something_else. So what's wrong with this?
The code can become hard to reason about/understand once you start mutating the variables. It can lead to bugs and control flow is not so nice. Maybe we are unable to perceive that pain in this trivial example, but this could become complicated quickly, once you use this approach in something like rails
So can we make it better? Yes! By extracting the mutation into a function we can write something which is easier to understand and easier to test
def do_something x = x_value puts "#{x} is bla bla" # use x for some other operation end def x_value initial_x_value = 1 return initial_x_value + 2 if something_else.even? initial_x_value end
By extracting the x_value
method, we removed the mutation completely from do_something
method and it's somewhat easier to follow than tracking what happened to variable x at this point. The bonus is you can easily test the x_value
independently without depending on testing do_something
method
Top comments (0)