views:

160

answers:

4

I have a class Request.cs

It has an abstract method:

public abstract Response CreateResponse(XmlReader reader);

and there's also a method:

public Response SendRequest(string requestURI)
{
    ...

    XmlReader reader = XmlReader.Create(responseStream);

    return CreateResponse(reader);
}

The CreateResponse method is implemented in a subclass that extends Request. And that implementation returns response.

I don't understand how you can return a method like this that's an abstract method but the value returned is actually in the implementation of the method from the subclass. Is this an example of the Template Method pattern or just simple polymorphism, or is this "tricky or too savvy" code or even messy? I'm trying to figure out how this can even be done (is this basic OOP principal or design pattern) and is this a good practice or good use of OOP?

+1  A: 

This is a very standard approach. In fact it's often recommended. The CreateResponse method is like a blank that has to be filled in by the derived class.

Daniel Earwicker
Thanks, I just wasn't sure...never saw that before.
so this is not a template method pattern or is it somewhat?
It's simpler if you just think of this as another form of parameterization - giving a name to a "gap" that must be filled in to make use of something; essentially the same idea as a function taking parameters, or a generic taking type parameters, and so on.
Daniel Earwicker
+1  A: 

Yes, this is template method. Since the Response class is abstract, you are forced to implement CreateResponse before you can call SendRequest. This way, the common logic is encapsulated in the base class and the rest of the logic can vary as needed (by creating multiple implementations of the base class).

Robin Clowers
Thanks for confirming that for me. Never used a Template Method before.
A: 

The main reason being that when you use the method, you never know about the details, just the interface and an abstract method has that defined.

Being as the method is abstract it has no details since they must be defined by the derived class. The main point that makes this possible is that the "INs" and "OUTs" never change as the method IS abstract in the base therefore the interface is defined, just not the implementation... yet.

Think of it like someone selling basic airline tickets from point A to B not knowing what airline was going to be used. They have no idea how you will get there yet but once they hand off the contract of the sold ticket to an airline, that airline will figure out the details of meeting the contracts terms. All you cared about when buying the ticket was that you knew for x dollars you were going to get from A to B.

Kelsey
A: 

This is template method, and template method is really not much more than simple polymorphism. This is exactly the kind of thing typical C# / Java -style OO polymorphism is intended for and is a good usage of the language.

Charlie Flowers