Skip to content

Working example with detailed commit history on the "collapse hierarchy" refactoring based on Fowler's "Refactoring" book

License

Notifications You must be signed in to change notification settings

kaiosilveira/collapse-hierarchy-refactoring

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Continuous Integration

ℹ️ This repository is part of my Refactoring catalog based on Fowler's book with the same title. Please see kaiosilveira/refactoring for more details.


Collapse Hierarchy

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.

Working example

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.

Test suite

The test suite is pretty simple and covers the getters of each class. That's all we need to be safe to proceed.

Steps

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!

Commit history

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.

About

Working example with detailed commit history on the "collapse hierarchy" refactoring based on Fowler's "Refactoring" book

Topics

Resources

License

Stars

Watchers

Forks

Sponsor this project