Edit Rename Upload Download Back to Top

polymorphism instead of a case statement

If the case statement needs to discriminate on classes that already exist, or that the programmer already naturally wants to create, then polymorphism is the OO way to go. I illustrate by a trivial example (FYI notation used in my Smalltalk examples)

If your application already has abstract class Vehicle and concrete subclasses Car and Truck, and if you want to extract the road tax for aVehicle, then it is far more sensible to type

   Vehicle>>tax
      ^self subclassResponsibility

   Car>>tax
      ^150 "or whatever extortionate sum it is"

   Truck>>tax
      ^300 "or whatever even more extortionate sum it is"

   Owner>>payTaxOn: aVehicle
      self pay: aVehicle tax.

than to type

   Owner>>payTaxOn: aVehicle
      aVehicle class switch	
         caseIs: Car then: [self pay: 150]
         caseIs: Truck then: [self pay: 300].

as the equivalent of (I use general curly-brackets pseudo-code below rather than strict Java, whose particular case statement limitations would obscure things)

   Owner>>payTax(aVehicle)
      switch(aVehicle.getClass())
         case 'Car' : {self.pay(150); break;}
         case 'Truck' : {self.pay(300); break;}

The case statement hardcodes the current hierarchy into a method which must be found and fixed whenever the hierarchy changes. By contrast, the polymorphic tax method can be sent to different classes of object, each of which will provide the appropriate implementation. As a result, methods which send it (such as the payTax method in the example) will still work when the vehicle subclasses are changed, when new subclasses are added, when the system is extended to pay tax on other things, etc. This is the OO way; say things once and once only.

Other approaches:

(Written by Niall Ross as part of Smalltalk for Java Programmers.)


Edit Rename Upload Download Back to Top