1

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.

Pugna
  • 57
  • 9
  • 1
    The inheritance will save you from `if`s when you're actually using `Filetype` instance. At some point you still need a way to check how to instantiate proper `Diletype` derived class. Often that task is delegated to something called a factory (either a factory method or a factory class) and this one still uses some kind of logic (`if` statements or `switch`) to create proper instance. Search for factory pattern to learn more. – MarcinJuraszek Jan 12 '15 at 00:03
  • possible duplicate of [Large Switch statements: Bad OOP?](http://stackoverflow.com/questions/505454/large-switch-statements-bad-oop) – Erik Funkenbusch Jan 12 '15 at 03:10

1 Answers1

1

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.

Leandro Caniglia
  • 14,495
  • 4
  • 29
  • 51