Monday, July 30, 2012

Introduce Middle Man

What is one has two classes where one class inherits from the other like so?

  1. namespace MiddleMan.Models
    {
       public class Crow : Animal
       {
          public Crow()
          {
             bearsLiveYoung = false;
             hasLegs = true;
             canFly = true;
             lifespan = 1;
          }
          
          public int lifespan {
             get { return base.lifespan; }
             set
             {
                if (value > 0 && value < 30)
                {
                   base.lifespan = value;
                }
             }
          }
       }
    }
  2. namespace MiddleMan.Models
    {
       public class Animal
       {
          public bool bearsLiveYoung { get; set; }
          public bool hasLegs { get; set; }
          public bool canFly { get; set; }
          public int lifespan { get; set; }
       }
    }

What if a third class is sandwiched between the two? What might we call this new item? A middle man?

Share photos on twitter with Twitpic
  1. namespace MiddleMan.Models
    {
       public class Crow : Bird
       {
          public Crow()
          {
             canFly = true;
             lifespan = 1;
          }
          
          public int lifespan {
             get { return base.lifespan; }
             set
             {
                if (value > 0 && value < 30)
                {
                   base.lifespan = value;
                }
             }
          }
       }
    }
  2. namespace MiddleMan.Models
    {
       public class Bird : Animal
       {
          public Bird()
          {
             bearsLiveYoung = false;
             hasLegs = true;
          }
       }
    }
  3. namespace MiddleMan.Models
    {
       public class Animal
       {
          public bool bearsLiveYoung { get; set; }
          public bool hasLegs { get; set; }
          public bool canFly { get; set; }
          public int lifespan { get; set; }
       }
    }

I think that is what Martin Fowler might call it. I think he might dub this sort of refactoring "Introduce Middle Man." I suppose I could be wrong.

No comments:

Post a Comment