Programming Flashcards
How would you explain the template method pattern?
Defining a basic structure in the superclass and sending messages to acquire subclass-specific contributions.
What maintainability rule should you employ when using the template method pattern?
Any class that uses the pattern must supply an implementation for every message it sends, even if it’s something like
def default_size raise NotImplementedError end
When refactoring using inheritance, what process should you use?
- Push concrete code down to the subclass
- Promote abstract code to the superclass
(This makes failures more explicit and less hidden.)
How do I know when inheritance may be a fit?
Does your code contain an if statement that checks an attribute that holds the category of self to determine what message to send to self?
What does a hook method look like?
In subclasses, implement methods in the subclass so it doesn’t have to call super.
def post_initialize(args) @tape_color = args[:tape_color] end
Why use hook methods?
If we have to call “super” in the subclass, the subclass has some knowledge of the algorithm. It’s cleaner to send hook messages that exist solely to provide subclasses a place to contribute information by implementing matching methods.
Is a Ruby class an object?
Yes.
What happens when methods are added to the Singleton class?
Any object can also have ad hoc methods added directly to its own personal “Singleton class”. These ad hoc methods are unique to this specific object.
What happens when Ruby doesn’t find a message the first time in the lookup chain?
Ruby gives the original receiver a second change by sending it a new message, method_missing, and passing :whatever as an argument. Attempts to resolve this new message restart the search along the same path, except now the search is for method_missing rather than spares.
What is an antipattern suggesting code could benefit from inheritance?
An object uses a variable with a name like “type” or category” to determine what message to send to self contains two highly related but slightly different types.
How can I know when I’ve overlooked a duck type?
When a sending object checks the class of a receiving object to determine what message to send.
Should I implement code in an abstract superclass that does not apply to every class that inherits it?
No. This creates quirks.
Must subclasses respond to every message in their superclasses’ interface?
Yes
What is an example of the template method pattern?
TODO: Furnish one.
Should a subtype be substitutable for its supertype?
Yes.