Oleh Devua
Oleh Devua

Reputation: 384

why is the assignment of instance variables to local variables is need in crystal?

In Crystal compiler source code I've seen such code

def dirname
  filename = @filename
  if filename.is_a?(String)
    File.dirname(filename)
  else
    nil
  end
end

def original_filename
  case filename = @filename
  when String
    filename
  when VirtualFile
    filename.expanded_location.try &.original_filename
  else
    nil
  end
end

def <=>(other)
  self_file = @filename
  other_file = other.filename
  if self_file.is_a?(String) && other_file.is_a?(String) && self_file == other_file
    {@line_number, @column_number} <=> {other.line_number, other.column_number}
  else
    nil
  end
end

So, what the reason to assign an instance variable to a local variable instead of using instance variable directly?

Upvotes: 1

Views: 147

Answers (1)

Julien Portalier
Julien Portalier

Reputation: 2999

Because @filename may be changed concurrently between the time we check if it's not nil (if @filename) and the time we access it. Crystal being a compiled program, would @filename not be the type it's expected to be, then the program would crash with a segfault.

By assigning to a local variable, we make sure the variable does exists.

Upvotes: 5

Related Questions