Skip to content

Latest commit

 

History

History
138 lines (87 loc) · 3.14 KB

File metadata and controls

138 lines (87 loc) · 3.14 KB

Refactoring 007 - Extract Class

Refactoring 007 - Extract Class

Behavior is repeated across the system. But we are missing a concept

TL;DR: Put together what belongs together

Problems Addressed

  • Code Duplication

  • Missing Abstraction

  • Low Cohesion

Related Code Smells

Code Smell 124 - Divergent Change

Code Smell 143 - Data Clumps

Code Smell 147 - Too Many Methods

Steps

  1. Extract the methods (and accidentally the properties) coupled into a new concept

  2. Use the new concept

Sample Code

Before

final class Person {
 
      private String name;
   
      // Below cohesive properties
      private String homeAreaCode;
      private String homeNumber;
      
      public String name() {
          return name;
      }
   
      // Below cohesive behavior
      public String telephoneNumber() {
          return ("(" + homeAreaCode + ") " + homeNumber);
      }
      String areaCode() {
          return homeAreaCode;
      }
      String officeNumber() {
          return officeNumber;
      } 
 }

After

// 1. Extract the methods (and accidentally the properties) 
// coupled into a new concept      
   public class TelephoneNumber {
   
      private String number;
      private String areaCode;
   
      public String telephoneNumber() {
          return ("(" + areaCode + ") " + number);
      }
      public String areaCode() {
          return areaCode;
      }
      public String number() {
          return number;
      }
   }
   
final class Person {

      private String name;
  
      // 2. Use the new concept
      private TelephoneNumber officeTelephone = new TelephoneNumber();
      
      public String name() {
          return name;
      }
      public String telephoneNumber() {
          return officeTelephone.getTelephoneNumber();
      }
     
  }

Type

[X] Automatic

Most IDEs implement this safe refactor.

Why is the Code Better?

Logic code is in just one place together with its rules

Safety

This is a safe refactoring.

Tags

  • Classes

Related Refactorings

Refactoring 002 - Extract Method

See also

Refactoring.com

Refactoring Guru

Credits

Image from drpepperscott230 on Pixabay


This article is part of the Refactoring Series.