You shouldn't inherit from String
, both for reasons of good object-oriented design and pure pragmatism.
If you inherit from String
, you are violating the Liskov Substitution Principle, which states that instances of subclasses should be substitutable for instances of their superclass. This is not the case here: I can insert a space in the middle of a String
, but I can not insert a space in the middle of a Tag
, therefore a Tag
is not a substitue for a String
, and thus shouldn't be a subclass.
And as a purely practical matter: you are inheriting roughly 100 public instance methods from String
. Do you really want to audit (and potentially override) every single one of them to ensure they don't violate Tag
's contract?
I would rather do something like this:
require 'facets/multiton'
class Tag
include Multiton
attr_reader :name
attr_accessor :description
private
def initialize name, description=nil
raise ArgumentError, 'Tag name cannot contain whitespace' if str =~ /\s/
self.name = name.to_s.dup.freeze
self.description = description unless description.nil?
end
attr_writer :name
def self.multiton_id name, description=nil
return name.to_s.downcase
end
end