|
I (happily) write a lot of OOP code, "inheritance is bad, use composition" is such a trite and unhelpful dogma that gets in the way of any actual discussion about where inheritance is useful. IMO, the case where inheritance makes the most sense is when you have a set of objects polymorphically answering some question, usually with a simple answer. class Subset
class Whole < Subset
def of(items)
items
end
end
class Range < Subset
def initialize(from:, to:)
@from = from
@to = to
end
def of(items)
items[@from:@to]
end
end
end
which is used as such: subset = Subset::Whole.new
puts subset.of(["a", "b", "c"]) # => ["a", "b", "c"]
subset = Subset::Range.new(from: 0, to: 1)
puts subset.of(["a", "b", "c"]) # => ["a"]
You can then pass around a Subset object anywhere (aka dependency injection) and push conditionals up the stack as far as possible.Simply saying "inheritance is bad" gets nobody anywhere. |