ℹ️ This repository is part of my Refactoring catalog based on Fowler's book with the same title. Please see kaiosilveira/refactoring for more details.
Before | After |
---|---|
class Employee { ... }
class Salesman extends Employee { ... } |
class Employee { ... } |
Often enough, simplicity pays off. This is also true when we reach clearer interfaces and relationships. The side-effect, though, is that sometimes we find out that we no longer need a certain hierarchies. This refactoring helps with collapsing those into the base class.
Our working example is a simple program that contains a class hierarchy formed by Person
and Student
, with the only difference being that Student
has an associated age
, while Person
does not. Our goal is to collapse Student
into Person
.
The test suite is pretty simple and covers the getters of each class. That's all we need to be safe to proceed.
We start by pulling up age
from Student
to Person
:
diff --git Person
export class Person {
- constructor(name) {
+ constructor(name, age) {
this.name = name;
+ this.age = age;
}
}
diff --git Student...
export class Student extends Person {
constructor(name, age) {
- super(name);
- this.age = age;
+ super(name, age);
}
}
Then, we update the calling code to use Person
instead of Student
:
diff --git client...
-const student = new Student('John Doe', 25);
+const student = new Person('John Doe', 25);
console.log(`Student name: ${student.name}, age: ${student.age}`);
Which free us remove the, now unused, Student
class:
-export class Student extends Person {
- constructor(name, age) {
- super(name, age);
- }
-}
And that's it!
Below there's the commit history for the steps detailed above.
Commit SHA | Message |
---|---|
0e5ea86 | pull up age from Student to Person |
ae45f4d | update calling code to use Person instead of Student |
ba4019a | remove unused Student class |
For the full commit history for this project, check the Commit History tab.