user72603
user72603

Reputation: 997

What is this? Template method or what?

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?

Upvotes: 0

Views: 313

Answers (4)

Charlie Flowers
Charlie Flowers

Reputation: 17427

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.

Upvotes: 0

Kelsey
Kelsey

Reputation: 47726

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.

Upvotes: 0

Robin Clowers
Robin Clowers

Reputation: 2160

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).

Upvotes: 1

Daniel Earwicker
Daniel Earwicker

Reputation: 116664

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.

Upvotes: 1

Related Questions