What Is Refactor And Why Is It Matter ?

For someone with no programming experience, the word “refactor” can be confusing at first because it’s mostly used in coding. For a simple explanation, refactoring is making something better or clearer without changing what it does.

1. Why Refactor When Nothing Changes?

“If it works, don’t touch it” is a principle that is still valid in the real world. Its truth is pragmatic and is recommended to some extent when we do not have enough understanding of the system we are working on. From a business perspective, refactoring feels unproductive when there are no new features added to the system, but just like a business, sometimes we need to restructure processes, reorganize people, and rearrange tasks to maximize outcomes. The programming process also needs refactoring to optimize the coding experience, which helps make source code more readable, maintainable, and scalable. These benefits, in turn, accelerate developers when adding new features or fixing bugs later on.

1.1 What is Readable Code?

Readable code is code written clearly so that another developer, or your future self, can read it quickly and understand what’s going on, sometimes just by inferring from variable names and function names. Some tactics that can be applied to ensure readable code are:

  • Clear naming: Variables, functions, and classes have names that clearly explain their purpose.
  • Short, focused functions: Each function does one thing and not many things.
  • Consistent formatting: Proper indentation, spacing, and line breaks are essential.
  • Avoids unnecessary complexity: No overly clever tricks, straightforward logic.
  • Helpful comments: Explain why instead of what.
  • Use of standard patterns: Code follows common conventions, allowing others to instantly recognize the structure.

1.2. What is Maintainable code ?

  • Readable: as explained above
  • Well-organized: The code is structured logically into modules, functions, or classes.
  • Consistent: Follows the same style, naming conventions, and patterns everywhere.
  • Well-tested: Covered by tests that catch bugs early and safely.
  • Documented: Has comments or documentation explaining why and how things work.
  • Flexible: Easy to modify, extend, or adapt without breaking the existing code.

1.3. What is Scalable code ?

  • Efficient: Uses memory and CPU wisely; avoids unnecessary heavy operations.
  • Modular: Pieces of code can be easily separated or duplicated.
  • Asynchronous/non-blocking when needed: Doesn’t freeze the whole system while waiting for a slow task.
  • Uses good architecture: clear layers; can be split into microservices or separate components if needed.
  • Uses proper data structures: For example, using a Map instead of a List for fast lookups.
  • Database scalability: indexing, caching, batching queries, sharding, etc.

2. Refactoring Safety

Because the goal is to keep the system working the same while rewriting code, there must be a metric indicating sameness or an early detection of differences in system behaviors. This is where Test Driven Development shines.

Writing tests is mistakenly overlooked by inexperienced developers. Beginners usually think that programming jobs are just about writing code, seeing it run, and then moving on to writing more code. Writing tests seems like extra work or an annoying requirement. This is understandable, just as a young man does not understand “karma.” The consequences of this oversight usually include:

  • Bugs keep coming back.
  • Bugs evolve when more code is added.
  • Take too much time for debugging
  • Source code becomes a mess, and a small change can take months to implement.

When bugs cause enough pain, developers gain more experience.

2.1. Test-Driven Development (TDD)

Test-Driven Development (TDD) is a software development process in which you write tests before writing the actual code.

TDD follows a repeating three-step loop:

  1. Write a failing test (yes, always fail first!)
    • The test describes what the code should do.
    • It fails because the feature doesn’t exist yet or the bug is not fixed yet.
  2. Write the minimum code needed to make the test pass
    • Not perfect code, just good enough to pass the test.
  3. Refactor – Clean up the code
    • Improve readability, maintainability, and scalability
    • Keep the tests passing.

Then, repeat the cycle for the next feature and bug fixes.

Tests ideally can simulate the UX that users will engage with on a real product. This can not be 100% achieved, but keeping this principle in mind will help a lot in writing good tests. Depending on how closely a test simulates real-world UX, tests can be classified into 3 levels: Unit Test, Integration Test, and E2E Test.

2.2 Unit Tests

Unit tests are ideal for testing the behaviors of a function or a class. In each unit test, we can assess the output of a function given a particular input. We can anticipate what inputs there may be, even unrealistic ones (hackers usually input unrealistic ones), to ensure our functions keep functioning regardless of the input. Unit tests can be used as a debugging tool, allowing us to test a part of the system directly without trying to reproduce issues via the UI/UX. For functions that are well guarded by unit tests, developers can feel more confident in making changes or refactoring, as bugs can be caught early.

2.3. Integration Test

Integration tests are tests that check how multiple parts of the system work together. Functions, classes, and flows can be tested on how they interact with each other inside a system. It ensures that every “piece” of the system is integrating properly. Similar to unit tests, we can anticipate and simulate flows to catch bugs early.

2.4. E2E Test

E2E (End-to-End) tests are the tests that simulate a real user using the real app by actually clicking buttons and typing text.

This is the ultimate form of testing that can catch bugs that unit or integration tests cannot. E2E tests assess the app in an environment closest to production. They validate the entire system from UI/UX to data storage. However, these are the hardest tests to conduct, as a real system needs to be deployed for E2E tests to execute. Simulating user behaviors through coding requires more effort. This is why many teams usually stop at integration tests, and it is totally acceptable when the majority of bugs can be caught at the level of integration testing. Writing E2E tests is time-consuming, so we should only write them for bugs that are unproducible at the integration test level. These bugs are high-level issues and should be addressed by high-level tests, primarily concerning concurrency, timing, and resources.

  • Race Condition: A situation where the correct behavior of a program depends on the relative timing or interleaving of multiple threads or processes. It involves uncontrolled timing, which can lead to incorrect results.
  • DeadLock: Two or more threads/processes are waiting on each other indefinitely, preventing progress. As the result, system freezes because resources are locked in a circular wait.
  • Livelock: Threads or processes keep changing state in response to each other but make no actual progress. As the result, CPU or threads are active, but nothing gets done.
  • Starvation: A thread never gets access to a needed resource or CPU because other threads dominate it. As the result, resource exists, but some threads never get a chance to execute.
  • Atomicity violation: A set of operations that should be executed as a single, indivisible unit is interrupted, causing incorrect results.
  • Order violation: Correct behavior depends on operations happening in a specific order, but the order is not guaranteed that eventually leads to incorrect results.
  • Heisenbug: A bug that disappears or changes when you try to observe it (e.g., by debugging, logging, or adding print statements). This sounds like quantum computing but yes, it does exists. These bugs often caused by concurrency, timing, or memory issues.
  • Data corruption: Shared data is modified concurrently without proper synchronization, resulting in invalid or inconsistent values.
  • Lost update: Two concurrent operations overwrite each other’s results, causing data loss.
  • Dirty read / inconsistent read: A thread reads a partially updated or uncommitted value from another thread or transaction and then produce wrong results.
  • Priority inversion: A low-priority thread holds a resource needed by a high-priority thread, causing the high-priority thread to wait unnecessarily.

In conclusion, to Refactor code safely, we need a lot of tests, good tests one !

Read more at:

Build – Secure – Evolve with the-tech-lead.com.


Leave a Reply