push-down-field-refactoring

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.


Push Down Field

Before After
class Employee {
  protected quota: string;
}

class Engineer extends Employee { ... }
class Salesman extends Employee { ... }
class Employee { ... }
class Engineer extends Employee { ... }
class Salesman extends Employee {
  private quota: string;
}

Inverse of: Pull Up Field

As it often happens with class hierarchies, we have some specific fields that was firstly thought to be common to all subclasses, but end up being relevant just for some of those. This refactoring gives a glimpse of what to do in these cases.

Working example

Our working example is a straightforward Employee class hierarchy:

classDiagram
    class Employee
    Employee <|-- Engineer
    Employee <|-- Salesman

    class Employee {
        name
        quota
    }
Loading

Our goal is to move the quota field down to Salesman, since it’s only used there.

Test suite

Our test suite covers the basic properties of Salesman:

describe('Salesman', () => {
  it('should have a name', () => {
    const salesman = new Salesman('Kaio');
    expect(salesman.name).toBe('Kaio');
  });

  it('should have a quota', () => {
    const salesman = new Salesman('Kaio');
    expect(salesman.quota).toBe(1.5);
  });
});

That’s the minimum we need in place to get going.

Steps

We start by copying the quota field into Salesman:

diff --git Salesman...
  constructor(name) {
    super(name, 1.5);
+   this.quota = 1.5;
  }

then we remove quota from Employee (and update the other subclass so they don’t need to provide this value any longer):

diff --git Employee...
   constructor(name) {
-    super(name, 0);
+    super(name);
   }

And that’s it!

Commit history

Below there’s the commit history for the steps detailed above.

Commit SHA Message
6b116ee copy quota field into Salesman
afe975e remove quota field from Employee

For the full commit history for this project, check the Commit History tab.

Visit original content creator repository https://github.com/kaiosilveira/push-down-field-refactoring

Comments

One response to “push-down-field-refactoring”

  1. sqojootsij Avatar

    hsowuonjpjizjmhlhisfjxvrthnkzf

Leave a Reply to sqojootsij Cancel reply

Your email address will not be published. Required fields are marked *