How to Refactor a Codebase?. Yes, that thing you wanted to do a… | by David Yu | Mar, 2022

Photo by Arnold Francisca on Unsplash

Today I will do what others won’t so tomorrow I can do what others can’t — Jerry Rice

  • To make our code maintainable in the future
  • To increase the readability of code
  • To reduce complexity
  • To improve code’s performance
  • To help future features to be easier implemented
  • Adding comments/documents can make the code easier to understand
  • Code is not under active changes.
  • Code meets the current code standard
  • When proper specs exist, rewrite might make more sense
  • The current code has functional bugs
  • When a new feature is being added
  1. Meet with a few developers who have worked on the code that you will refactor
  2. Come up with a step by step plan with the team
  3. Inform the other parts of the team about the plan
  1. Test One Thing at a Time in Isolation
  2. Follow the AAA Rule: Arrange, Act, Assert
  3. Write Tests That Reveal a Bug, Then Fix It
  4. Name Your Tests Clearly and Don’t Be Afraid of Long Names
  5. Make Each Test Independent
  6. Run test often

Some tips for understanding what the code does:

  • Run the code
  • Run debugger with code
  • Find the entry point
  • Visualize the connections
  • Talk to the users
  • Talk to someone who worked on the code before

Retrace to source

  1. look at the UI to see what looks similar
  2. use “Inspect Element” in the console to locate some information that you could use to search for that code
  3. If they are actually two(or more) different pieces of code, turn them into a reusable component
  4. Whenever possible, separate presentational component from functional
  1. Focus on one endpoint at a time
  2. Search for the endpoint keywords to find the entry code, eg “/user”
  3. If looking for a keyword doesn’t work, look for the entry point of the backend service. Then understand how the endpoint gets setup
  4. Find other service/function that the endpoint depends on
  5. Think about how to reduce the steps to get to the current response(output of the endpoint)

Using global search for keywords

Visualize whenever possible

  1. Free:
  2. Not so free: Lucidchart

Measuring programming progress by lines of code is like measuring aircraft building progress by weight. — Bill Gates

  • Arrange → Understand → Rename → Remove Redundancy
  • Understand → Rename → Arrange → Remove Redundancy

Exit early

Avoid Nested Ternary

Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — John Woods

git commit -m 'renamed variables'
git commit -m 'renamed variables in profile page'

Leave a Comment