You might have heard that classes should have a single responsibility. Even if
you try to follow this dogma, in practice classes grow. Some operations are,
some more data is added, and sooner or later your class has more than one
The Extract Class refactoring is best applied if there are logical units of
data which are grouped together, or operations which are just performed on a
subset of the data.
- Step 1
Determine what to extract
Find logical units of data which are grouped together or operations which are performed on a subset of the data.
- Step 2
Create a New Class
Create a new class with the extracted operations and establish a link from the old to new class. This link might be bidirectional.
- Step 3
Rename the Old Class
If the name of the old class is not fitting anymore, consider renaming it.
- Step 4
Review the interfaces and links of each class
The goal should be minimally coupled classes. Examine both classes to see if you can replace a bidirectional relationship with a unidirectional relationship.
- Step 5
Value object vs. reference object
Decide whether you would like to expose the new object as a value object (immutable), or a reference object (may be modified).
Example: Moving Related Fields to Value Object
Step 3: Rename old class
In our case, the name of the old class is still fitting, we do not need to
rename it. So, we will just skip this step.
Step 4: Review Interfaces and Links of each class
Our classes only have a unidirectional link, the
Text class does not know
where it is being used, and it also does not need to know. This also allows us
to use the
Text class in classes other than
BlogPost. So, there is
nothing to change here as well.
Step 5: Value Object vs. Reference Object
In general, prefer to use a value object as this limits the scope of how and
when the object can be modified. In our case, we decided to use a value object:
If the text is changed, a new object must be created. This way we ensure that
any modification must go through the owning class, in our case