mercredi 23 septembre 2015

Conditional to polymorphism - a more complicated case

Say I have this well known example:

   double getSpeed() {
       switch (_type) {
           case EUROPEAN:
              return getBaseSpeed();
           case AFRICAN:
              return getBaseSpeed() - getLoadFactor() * _numberOfCoconuts;
           case NORWEGIAN_BLUE:
              return (_isNailed) ? 0 : getBaseSpeed(_voltage);
       }
       throw new RuntimeException ("Should be unreachable");
   }

Obviously, I'd refactor into subclasses and everything will be made right in the world again. But what if I have:

   double getSpeed() {
       switch (_type) {
           case EUROPEAN:
              inform_gary(_count);  
              return getBaseSpeed();
           case AFRICAN:
              increment_package_counter();
              transmit_coordinates(_coordinates);
              return getBaseSpeed() - getLoadFactor() * _numberOfCoconuts;
           case NORWEGIAN_BLUE:              
              return (_isNailed) ? 0 : getBaseSpeed(_voltage);
       }
       throw new RuntimeException ("Should be unreachable");
   }

Now it would be useless to subclass because then I'd have to tightly couple the subclasses to code they shouldn't know about. Is there a solution to this problem?

Aucun commentaire:

Enregistrer un commentaire