SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Nov 2006
    Posts
    19
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    'Polymorphism' instead of Switch?

    I've read some obscure arguments here and there as to why 'polymorphism' should be used instead of switch in certain, if not most cases. My problem is, while I'm fairly new to javascript and have some vague understanding of what polymorphism is, I can't seem to figure out how it could be a replacement for a switch function; maybe because I really don't understand what it is, and there doesn't seem to be much information on the subject in relation to Javascript's switch function.

    Is there a clear explanation of this available somewhere, or could someone jot down a quick 'polymorphic' switch function for me to have a look over? Much appreciated.

  2. #2
    Caveat surfer Buddy Bradley's Avatar
    Join Date
    May 2003
    Location
    Cambridge, UK
    Posts
    2,366
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I don't know what you've been reading, but the OO concept of polymorphism and JavaScript's switch() function have nothing to do with each other.

    Polymorphism is where you have two object namespaces that both implement a method with the same name - for example, you might have a Man object and a Country object which both have a .fullName method; they can have the same name even though the underlying code for both .fullName methods is different, because they are within different namespaces.

    Edit: I guess you could use polymorphism as a replacement for switch() by instantiating the thing you are switch()ing as one of a selection of objects, all of which have the same method - it would have to be a very specific type of application you were writing, though.
    Last edited by Buddy Bradley; Dec 30, 2006 at 09:21. Reason: Add further thoughts

  3. #3
    SitePoint Aficionado JVLB's Avatar
    Join Date
    Jan 2002
    Location
    N 44 56.537' W 123 3.683'
    Posts
    1,127
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That's a good analysis, Mr. Bradley. I might add that since polymorphism relies on object type or class to, in essence, determine the case to execute, it's hard to imagine it being of much use when the determining factor for code branching is something other than that type, such as a factor external to the object itself.

  4. #4
    SitePoint Member
    Join Date
    Nov 2006
    Posts
    19
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ah, maybe thats why I couldn't put the two together

    If you google polymorphism and switch you can find some topics related to replacing switch with polymorphism, though I can't say I understood any of them.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •