Improve code cohesion and readability by moving related fields and methods from one class to a new class.
This technique is used to move a group of related fields and methods from one class to a new class, in order to improve the cohesion and readability of the codebase. This can be useful when a class has grown too large or has too many responsibilities, making it difficult to understand or maintain. Additionally, it allows for reusing the extracted class in other parts of the codebase.
For example, consider the following class, which has a name, email, and address fields, as well as several methods that operate on these fields:
}
}
}
}
}
}
}
}
}
}
To improve the cohesion and readability of this class, we can extract the name, email, and address fields and related methods into a new class called ContactInfo:
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
In this example, we have extracted the name, email, and address fields, as well as the related getter and setter methods, into a new class called ContactInfo. This improves the cohesion of the Customer class by focusing on its primary responsibilities of saving and sending invoices, while the ContactInfo class focuses on storing and manipulating contact information. Additionally, it makes the code more readable, as the fields and methods related to contact information are now in a separate class, reducing the complexity of the Customer class.