Skip to main content

Dynamic Polymorphism - Why, What, How

Dynamic means "run-time."

Polymorphism means "multiple shapes."

Synonyms for dynamic polymorphism include "runtime polymorphism" and "dynamic method dispatch."

If you are a "traditional" relational database developer, these terms might sound unfamiliar. But how about overloading? Are you familiar with that?

Overloading occurs when you have more than one subprogram (procedure and/or function) with the same name in the declaration section of a block, package specification or package body. These subprograms need to differ by parameter list or type (procedure vs function) in a way that is sufficient for the compiler to distinguish.

Well, guess what? Another name for overloading is "static polymorphism."

Static means "compile-time."

Polymorphism means "multiple shapes."

Why, you might be wondering, does the Oracle Database need to wait till runtime to determine which method in which type in the hierarchy should be called?

After all, it doesn't have any troubling sorting that out with overloading of subprograms in packages!

The answer to that question lies in one word: substitutability.

It's a topic I've touched on both directly and indirectly in my previous posts in this series. The best way to think about substitutability is that if I have the following type hierarchy....
CREATE TYPE food_ot AS OBJECT (
   name        VARCHAR2(100),
   food_group  VARCHAR2 (50),
   grown_in    VARCHAR2 (100)
   )
   NOT FINAL
   ;

CREATE TYPE dessert_t UNDER food_ot (
   contains_chocolate  VARCHAR2(1),
   year_created        NUMBER(4)
   )
   NOT FINAL
   ;
....then this follows:
Every dessert is a food, but not every item of food is a dessert.
And now with the S word:
Where I have an instance of food, I can substitute it with an instance of dessert.
This ability to substitute is precisely what drives the need for dynamic polymorphism in object-oriented languages. Let's find out why.

Since polymorphism has to do with choosing the right method, let's enhance my food-related hierarchy to include a member method in each type.
CREATE TYPE food_ot AS OBJECT (
   name VARCHAR2 (100),
   food_group VARCHAR2 (100),
   grown_in VARCHAR2 (100),
   MEMBER FUNCTION price
      RETURN NUMBER
)
   NOT FINAL;
/

CREATE OR REPLACE TYPE BODY food_ot
IS
   MEMBER FUNCTION price
      RETURN NUMBER
   IS
   BEGIN
      RETURN (CASE self.food_group
                 WHEN 'PROTEIN' THEN 3
                 WHEN 'FRUIT' THEN 2
                 WHEN 'VEGETABLE' THEN 1
              END);
   END;
END;
/

CREATE TYPE dessert_ot
   UNDER food_ot (
      contains_chocolate VARCHAR2 (1),
      year_created NUMBER (4),
      OVERRIDING MEMBER FUNCTION price
         RETURN NUMBER
   )
   NOT FINAL;
/

CREATE OR REPLACE TYPE BODY dessert_ot
IS
   OVERRIDING MEMBER FUNCTION price
      RETURN NUMBER
   IS
   BEGIN
      RETURN 100;
   END;
END;
/
I'm keeping the price formula really simple for desserts. :-)

And now consider the following block:
DECLARE
   TYPE foodstuffs_nt IS TABLE OF food_ot;

   fridge_contents   foodstuffs_nt
      := foodstuffs_nt (food_ot ('Brussels Sprouts', 'VEGETABLE', 'Farm'),
                        dessert_ot ('Strawberries',
                                   'FRUIT',
                                   'Backyard',
                                   'N',
                                   2001));
BEGIN
   FOR indx IN fridge_contents.FIRST .. fridge_contents.LAST
   LOOP
      DBMS_OUTPUT.put (
            CASE
               WHEN fridge_contents (indx) IS OF (ONLY food_ot)
               THEN
                  'Food'
               WHEN fridge_contents (indx) IS OF (ONLY dessert_ot)
               THEN
                  'Dessert'
            END
         || ' price:');

      DBMS_OUTPUT.put_line (fridge_contents (indx).price ());
   END LOOP;
END;
/
We can see from this code why overloading or static polymorphism is not sufficient when it comes to executing the right method.

When the block is compiled, the PL/SQL engine knows that the fridge_contents nested table is filled with instances of type food_t. It could even, I suppose, notice that the nested table contains instances of food_t and dessert_t.

But it sure is hard to see how at compile time. the PL/SQL engine would know which price method should be used in the call to DBMS_OUTPUT.PUT_LINE. After all, fridge_contents (indx) at compile time is of type food_t (and, of course, because of substitutability, it could also be any subtype of food_t, but what compiler could sort that out?).

It is only when the block is executed that PL/SQL can check to see the actual type of the instance in that element of the collection and invoke the appropriate method.

And as you can see from my use of the IS OF syntax, it is possible for both us and the PL/SQL engine to get that type.

You can run this code for yourself on LiveSQL.

Check Out the Entire Series

Visit this post that gives you quick access to all the articles in the series.


Comments

  1. Hi Steven! Recently I "found" some cool use for polymorphism: to pass function as parameter. Looks like inventing bycicle :) We make parent object type with one function-method without parameters and use this type as parameter type where we need function as parameter. Then we make child object types where overwrite single method and use object type fields as parameters, make constructor for them. Now we can instantiate child objects and pass them as parameters and call their single method.
    But why we need to pass function as parameter? :) I often need to pass selects with same structure, now I use pipelined table function-methof for it.

    ReplyDelete
    Replies
    1. Sounds really interesting, Vasily. I wonder if you might be able to publish a script on LiveSQL.oracle.com that demonstrates the technique?

      Delete
  2. Hello Steven Sir,
    Namaskar.
    Outstanding (all the articles in the series).

    ReplyDelete

Post a Comment

Popular posts from this blog

Quick Guide to User-Defined Types in Oracle PL/SQL

A Twitter follower recently asked for more information on user-defined types in the PL/SQL language, and I figured the best way to answer is to offer up this blog post. PL/SQL is a strongly-typed language . Before you can work with a variable or constant, it must be declared with a type (yes, PL/SQL also supports lots of implicit conversions from one type to another, but still, everything must be declared with a type). PL/SQL offers a wide array of pre-defined data types , both in the language natively (such as VARCHAR2, PLS_INTEGER, BOOLEAN, etc.) and in a variety of supplied packages (e.g., the NUMBER_TABLE collection type in the DBMS_SQL package). Data types in PL/SQL can be scalars, such as strings and numbers, or composite (consisting of one or more scalars), such as record types, collection types and object types. You can't really declare your own "user-defined" scalars, though you can define subtypes  from those scalars, which can be very helpful from the p...

The future of Oracle PL/SQL: some thoughts on Sten Vesterli's thoughts

Sten Vesterli published a very thought-provoking post on his blog: Please stop reading this post, and read that one. When you are done, come on back here for my thoughts on Sten's thoughts. OK. You read it. Here we go. First, thanks, Sten, for being such an interesting, wise, sometimes provocative voice in our community. Next, Sten writes: Now, on the one hand, I certainly agree that the vast majority of young developers are currently caught up in the modern version of a Gold Rush, which is: "Build an app using JavaScript, pay no attention to that database behind the curtain." But I can assure you that I still do meet young PL/SQL programmers, regularly, when I am at conferences and doing onsite presentations at companies. So, young person who writes PL/SQL: do not be afraid! You are not alone! And you are super-smart to have made the choice you did. :-) Next, Sten offers this advice to managers: I agree that PL/SQL is a "spec...

Table Functions, Part 1: Introduction and Exploration

Please do feel encouraged to read this and my other posts on table functions, but you will learn much more about table functions by taking my Get Started with PL/SQL Table Functions class at the Oracle Dev Gym. Videos, tutorials and quizzes - then print a certificate when you are done! Table functions - functions that can be called in the FROM clause of a query from inside the TABLE operator - are fascinating and incredibly helpful constructs. So I've decided to write a series of blog posts on them: how to build them, how to use them, issues you might run into. Of course, I am not the first to do so. I encourage to check out the  documentation , as well as excellent posts from Adrian Billington (search for "table functions") and Tim Hall . Adrian and Tim mostly focus on pipelined table functions, a specialized variant of table functions designed to improve performance and reduce PGA consumption. I will take a look at pipelined table functions in the latter part...