DEV Community

Ted M. Young
Ted M. Young

Posted on • Edited on

Live Coding Learnings - June 20, 2019

Pure Refactoring

I didn't stream today, but was reviewing some of my past streams (mining it for content for my Java coaching clients) and realized my coding rule that I mentioned earlier was incomplete. The rule I stated was:

Do not change code unless it is to make a failing test pass (or fail better).

However, I had forgotten that this rule doesn't apply when doing pure refactoring. In that case, the rule is:

Tests must pass before refactoring and remain passing -- with no changes -- after refactoring.

Some might say that this is too strict, and I'd agree, I'll bend these rules when using my judgment, but for teaching novices, it's a good way to differentiate when you're changing code to add capabilities vs. when you're changing internals to improve the code itself. The latter is refactoring and if tests are breaking, you're either changing too much, or your tests were too low-level (tied too tightly to the implementation details).

For example, if I have the code

public int price() {
  return cachedPrice;
}

Then it shouldn't matter to tests or other code if I changed it to:

public int price() {
  int sum = 0;
  for (Item item: items) {
    sum += item.price();
  }
  return sum;
}

In other words, whether I calculate the price when requested, or cache it (the first example), it's an implementation detail that the class should be free to change, i.e., refactor, without affecting other code.

If tests are relying on one or the other behavior, then that's likely (though not always) a problem where you might want to re-think your test code.


Be sure and tune in to my next live coding stream: https://twitch.tv/jitterted.

Top comments (3)

Collapse
 
stargator profile image
Stargator

What do you use in order to stream? Whether applications or equipment?

Collapse
 
jitterted profile image
Ted M. Young

I have a Mac and wrote about my setup here: tedmyoung.com/live-coding-on-twitch/

with a follow-up here: tedmyoung.com/remote-pair-programm...

If you have Windows, the details will be different, but OBS (obsproject.com/) is still the software that you'd use.

Collapse
 
stargator profile image
Stargator

Thanks, I have a Mac too. I'll check this out.