viphat / til

Today I Learned
http://notes.viphat.work
0 stars 1 forks source link

When To Refactor #272

Open viphat opened 6 years ago

viphat commented 6 years ago

Source

Here are seven cases when refactoring can help

When you need to make a change but it's difficult to do so.

Instead of trying to make a difficult change, first, refactor the code so you can make the change easily. Then make the easy change.

When you need to understand a piece of code

When trying to understand a piece of unfamiliar code, play around with the code first. If some parts of it require efforts to understand, try to refactor the code to make it more understandable. The refactored code should reflect your understanding. Rerun the tests after each refactoring to make sure your understanding is correct.

Using refactoring as a way to understand a piece of code has two benefits:

Three strikes and you refactor

Read more

  1. The first time you do something, you just do it.
  2. The second time you do something familiar, you wince at the duplication, but you do the duplicate thing anyway.
  3. The third time you do something familiar, you refactor.

When you try to debug or fix a bug

Similar to case 2, you need to understand the code in order to debug it.

When you do code reviews

Similar to case 2, understand the code is one of the first steps of doing code reviews.

When you just implemented a feature

After you implemented a feature, take a step back and think if there's any way to improve your code before merging it into the production branch.

When you feel stressed or tired of reading too many messy codes

Like computers have RAM, we, human, have working memories. According to MedicineNet, working memory is a system for temporarily storing and managing the information required to carry out complex cognitive tasks such as learning, reasoning, and comprehension.

As a complex cognitive task, programming utilize working memories. Unfortunately, each time we encounter a piece of messy code, as much as we want to ignore it, we can't help but add it to our working memories.

We say to ourselves: 'uh, this is ugly, but I don't have time for it now. I need to move on with my current task, but hopefully, I can come back and clean it up later.'

As time goes by, our working memories are filled with thoughts about messy code. Working at a messy office is rarely productive. Similarly, programming, which essentially is about learning and reasoning, when our heads are filled with thoughts about messy code can rarely be effective.

We need to clean and organize the office to make it pleasant again. Similarly, we can use refactoring, or Therapeutic Refactoring if you may, to clean up our working memories so we can return as happy and productive programmers.