IMCY IMCY - 4 months ago 9
Ruby Question

template method pattern, where to define common used functions

Thanks for your time!

I recently read about template pattern(in Ruby) and want to use this pattern in my codes.

My question is "where to put some commonly used functions".

Say I have TemplateRequestBody, JSONRequestBody and XMLRequestBody as following.

class TemplateRequestBody
def pretty_format
raised "called abstract method: pretty_format"
end
end

class JSONRequestBody < TemplateRequestBody
def pretty_format
# pretty format JSON
add_new_line_to_tail();
end
end

class XMLRequestBody < TemplateRequestBody
def pretty_format
# pretty format XML
escape_double_quotes();
add_new_line_to_tail();
end
end


In this example,
add_new_line_to_tail()
would be used by all child classes;
escape_double_quotes()
would be used only by some of the child classes.

Where should I implement these two functions? In TemplateRequestBody or?

Thanks!

Answer

As it always is - it depends :)

If a method will be shared across subclasses, putting it in the parent class (TemplateRequestBody) would make sense. If the methods will not be shared across the subclasses, then don't put them.

If method is going to be used by some of the classes, maybe you could think if a mixin would be a good place to store that method? Also, putting it in the parent class won't be a terrible idea.

Hope that helps!