Notes on ‘Refactoring ‘ — 3.5 Replace subclass with Fields

Before Refactor

class Person{
   boolean isMale(){}
}

class Male extends Person{
   boolean isMale(){
       return true;
   }
}

class Female extends Person{
   boolean isMale(){
       return false;
   }
}

After Refactor

class Person{
   private boolean male;  
   private Person(male){
     this.male = male; 
   }
   boolean isMale(){
     return male;
   }
   Person createMale(){
      return new Person(true);
   }
   Person createFemale(){
      return new Person(false);
   }

}


Benefits: Avoid the complexity of subclassing

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.