Comparison of Inheritance and
Case Statements Equivalents

Updated: 12/11/2000

Below is an attempt to compare the effects of inheritance, and its equivalence, on code size between OOP and a procedural equivalent. I used a pseudo-code style which attempts to not give any biased advantage to one side or the other.

The example below has a roughly even mix of inheritance and direct implementation (overrides) and an even mix of methods (operations) and subtypes (classes). Rather than describe the inheritance pattern used, I will use a table because I think tables are usually better at showing such patterns than code.

  Method
Subclass 1 2 3 4 5
A I - - - -
B I I - - -
C I I I - -
D I I I I -
E I I I I I
"I" = Inherited Implementation
"-" = Explicit Implementation
Parent not shown here, but would
obviously contain only dashes

As you can see, the examples show no significant code-size advantage of one paradigm over the other in this little experiment. You will also notice that the complexity is roughly the same (subjectively judged due to the lack of agreed-upon metrics).

Listing 1 - Procedural Version

    1 sub 1(handle)
    2    // all share same implementation, thus no case statements
    3 endSub
    4 sub 2(handle)
    5    select handle.type    // the type field of table handle
    6    case a
    7      a2_blah...
    8    case else    // sometimes called "otherwise"
    9      p2_blah...
   10 endSub
   11 sub 3(handle)
   12    select handle.type
   13    case a
   14      a3_blah...
   15    case b
   16      b3_blah...
   17    case else
   18      p3_blah...
   19 endSub
   20 sub 4(handle)
   21    select handle.type
   22    case a
   23      a4_blah...
   24    case b
   25      b4_blah...
   26    case c
   27      c4_blah...
   28    case else
   29      p4_blah...
   30 endSub
   31 sub 5(handle)
   32    select handle.type
   33    case a
   34      a5_blah...
   35    case b
   36      b5_blah...
   37    case c
   38      c5_blah...
   39    case d
   40      d5_blah...
   41    case else
   42      p5_blah...
   43 endSub

Listing 2 - OOP Version

    1 class Parent
    2    method 1
    3       p1_blah...
    4    method 2
    5       p2_blah...
    6    method 3
    7       p3_blah...
    8    method 4
    9       p4_blah...
   10    method 5
   11       p5_blah...
   12 endClass
   13 class A
   14    method 2
   15       a2_blah...
   16    method 3
   17       a3_blah...
   18    method 4
   19       a4_blah...
   20    method 5
   21       a5_blah...
   22 endClass
   23 class B
   24    method 3
   25       b3_blah...
   26    method 4
   27       b4_blah...
   28    method 5
   29       b5_blah...
   30 endClass
   31 class C
   32    method 4
   33       c4_blah...
   34    method 5
   35       c5_blah...
   36 endClass
   37 class D
   38    method 5
   39       d5_blah...
   40 endClass
   41 class E
   42    // inherits all, thus no explicit methods
   43 endClass


OOP Critique | Shape Example