Suppose I have the following
class AbstractClass; end
class ConcreteClass1 < AbstractClass; end
class ConcreteClass2 < AbstractClass; end
How do I document a return value that returns a class instance of a class that inherits AbstractClass (either ConcreteClass1 or ConcreteClass2) ? I want to focus on the fact that the return value can be either ConcreteClass1
or ConcreteClass2
but what matters is that they are all kind_of(AbstractClass)
I was thinking of something like this, is it the good approach ?
# Class MyClassFactory implements the factory pattern for selecting the appropriate class for xxx
def MyClassFactory
# @return [? < AbstractClass] an instance of a class inheriting AbstractClass
def create_instance(*args)
if cond?
ConcreteClass1
else
ConcreteClass2
end.new(*args)
end
end
Now suppose my method returns the class itself, and not a class instance, would this be the good approach ?
def MyClassFactory
# @return [? <= AbstractClass] the class to be used
def select_class
if cond?
ConcreteClass1
else
ConcreteClass2
end
end
end
It's sufficient to write
# @return [AbstractClass]
The reader should assume that Liskov substitution may apply. The Abstract
prefix (as well as an @abstract tag) will also communicate this clearly, and the resulting documentation will list ConcreteClass1
and ConcreteClass2
under the "Direct Known Subclasses" of AbstractClass
.
As for returning a class, the YARD creator's recommendation is to use Class<AbstractClass>
.