Refactoring Day 4 : Push Down Method


Yesterday we looked at the pull up refactoring to move a method to a base class so mutiple derived classes can use a method. Today we look at the opposite. Here is the code before the refactoring:

   1: public abstract class Animal
   2: {
   3:     public void Bark()
   4:     {
   5:         // code to bark
   6:     }
   7: }
   8:  
   9: public class Dog : Animal
  10: {
  11: }
  12:  
  13: public class Cat : Animal
  14: {
  15: }
</p>
So here we have some code with a base class that has a Bark method. Perhaps at one time our cat could bark, but now we no longer need that functionality on the Cat class. So we “Push Down” the Bark method into the Dog class as it is no longer needed on the base class but perhaps it is still needed when dealing explicitly with a Dog. At this time, it’s worthwhile to evaluate if there is any behavior still located on the Animal base class. If not, it is a good opportunity to turn the Animal abstract class into an interface instead as no code is required on the contract and can be treated as a marker interface.
   1: public abstract class Animal
   2: {
   3: }
   4:  
   5: public class Dog : Animal
   6: {
   7:     public void Bark()
   8:     {
   9:         // code to bark
  10:     }
  11: }
  12:  
  13: public class Cat : Animal
  14: {
  15: }
</p>

This is part of the 31 Days of Refactoring series. For a full list of Refactorings please see the original introductory post.

Refactoring Day 3 : Pull Up Method