jeudi 17 septembre 2015

Eliminate code duplication without multiple inheritance

Given the code above:

class Animal {
  getType()  return 'Normal'
  getSound() return 'No sound'
}

class Dog inherits Animal {
  getSound() return 'Au au'
}

Now you want to create a SuperDog:

class SuperDog inherits Dog {
  getType() return 'Super';
}

But them you realise that you can have multiple animals like:

class SuperCat inherits Cat {
  getType() return 'Super';
}

How would you eliminate the code duplication completely?

  • Using single inheritance language.
  • Composition would add the necessity to add proxy methods.
  • Traits (as just copy and paste code) can solve this nicely. This perhaps is a nice use case for them, but I wonder how to solve this without them.

Aucun commentaire:

Enregistrer un commentaire