Created
May 30, 2022 08:33
-
-
Save schmidt/e846087810033cac62fcd2bfd3c31ace to your computer and use it in GitHub Desktop.
Easier inheritance when implementing `==`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Point | |
attr_reader :x | |
attr_reader :y | |
def initialize(x:, y:) | |
@x = x | |
@y = y | |
end | |
# def ==(other) | |
# self.class == other.class && | |
# @x == other.x && | |
# @y == other.y | |
# end | |
def ==(other) | |
other.is_a?(Point) && | |
x == other.x && | |
y == other.y | |
end | |
end | |
class PolarPoint < Point | |
attr_reader :angle, :radius | |
def initialize(angle:, radius:) | |
@angle = angle | |
@radius = radius | |
end | |
def x | |
radius * Math.cos(angle) | |
end | |
def y | |
radius * Math.sin(angle) | |
end | |
end | |
p1 = Point.new(x: 1, y: 0) | |
p2 = PolarPoint.new(angle: 0, radius: 1) | |
# Reflexivity | |
p1 == p1 # => true | |
p2 == p2 # => true | |
# Symmetry | |
p1 == p2 # => true | |
p2 == p1 # => true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When using
to implement
==
there's no way forPolarPoint
to work as a drop-in replacement forPoint
. UnlessPolarPoint
performs some serious meta-programming magic and overwrites#class
, it can never be equal to aPoint
. By usingis_a?
we're giving the related / derived class more power. Futhermore, by usingother.is_a?(Point)
instead ofother.is_a?(self.class)
we can make sure that "Symmetry" works out of the box.If we're using
other.is_a?(self.class)
in the base implementation inPoint#==
as suggested in my tweet, we lose symmetry. Thenp1 == p2
butp2 != p1
. But at least we can fix that by implementing an adjustedPolarPoint#==
to re-establish symmetry. That's something that would not be possible when comparing#class
.All of this all is only relevant when
Point
is part of a library/gem. If it's all your application code, you can of course easily adjust the implementation ofPoint#==
when you introducePolarPoint
.