Pugna
Pugna

Reputation: 57

Using Polymorphism instead of Switch

Here is the logic: The server prepares the file (like index.html, or some.pdf) that it is going to send through HTTP response. Based on the suffix I wanna set the Content-type in HTTP header.

The logic now is I have Class Filetype, with lots of specific filetype subclasses extending it. But still I need to use "switch" to identify the suffix. Something like:

Filetype f = null;
if(suffix == "pdf"){
    f = Filetype_pdf(source);
} else if (suffix == "html") {
    f = Filetype_text(source);
}

But I use inheritance just to avoid these "if"s. Any advice to this issue or is this the way it should be? Thanks.

Upvotes: 1

Views: 130

Answers (1)

Leandro Caniglia
Leandro Caniglia

Reputation: 14858

Let's say that you have the following hierarchy:

Filetype
    HTMLType
    PDFType
    TxtType

Now assume that each of these classes understands the type message (not their instances, the class). Then you can create a class method in Filetype namely classFor that receives one argument extension and responds the subclass of Filetype that handles that extension. The implementation of classFor consists in enumerating all the subclasses looking for the subclass whose type matches extension.

In Smalltalk this would look like

classFor: extension
    ^Filetype allSubclasses detect: [:cls | cls type = extension]

Of course, there is an if message somewhere in the implementation of detect, but your code does not see it and elegantly expresses the condition that must be met.

EDIT:

The beauty if this approach is that the method classFor that detects the appropriate subclass will not change if you add (or remove) other subclasses that support new types of files. This contrasts with the switch statement that must name all the possibilities exhaustively. By avoiding the switch your code acquires the generality required to keep working with newer versions of your hierarchy.

Upvotes: 1

Related Questions