0

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?

Oleh Devua
  • 364
  • 6
  • 12

1 Answers1

4

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.

Julien Portalier
  • 2,959
  • 1
  • 20
  • 22