In ruby you can internally access variables directly via @var_name
or via private getters attr_reader :var_name
.
Which solution is more (semantically?) correct? Any advantages/disadvantages of using either solution 1 or solution 2?
Solution 1:
class Point
def initialize(x, y)
@x = x
@y = y
end
def distance
Math.sqrt(@x ** 2 + @y ** 2)
end
end
Solution 2:
class Point
def initialize(x, y)
@x = x
@y = y
end
def distance
Math.sqrt(x ** 2 + y ** 2)
end
private
attr_reader :x, :y
end
I would use the second option:
class Point
def initialize(x, y)
@x = x
@y = y
end
def distance
Math.sqrt(x ** 2 + y ** 2)
end
private
attr_reader :x, :y
end
For two reasons:
attr_reader
might be faster (as Filip Bartuzi already pointed out)attr_reader
might make it easier to refactor that class later on by replacing the attr_reader
with a custom getter method.