askvity

What is Rule of Thumb in Computer Science?

Published in Code Refactoring Guideline 3 mins read

In computer science, a "rule of thumb" generally refers to a practical guideline or principle based on experience rather than strict theory or proof. It's a simple, easily applicable concept used to make decisions or estimations, especially in the absence of precise data or rigorous methods.

Based on the provided reference, a specific and common rule of thumb in computer science, particularly in the context of code refactoring, is known as the "Rule of Three".

The Rule of Three

The Rule of Three is a guideline used to help programmers decide when duplicated code should be extracted into a reusable procedure (like a function or method).

  • The Principle: This rule states that you are allowed to copy and paste a piece of code once. However, if the same code fragment appears for a third time, it's a strong indicator that it should be factored out into a single procedure that can be called from multiple locations.
  • Purpose: The primary goal is to avoid code duplication, which is a violation of the DRY (Don't Repeat Yourself) principle.

Why is this Rule Important?

Following rules of thumb like the Rule of Three helps improve code quality and maintainability:

  • Reduces Redundancy: Eliminating duplicate code means the same logic isn't scattered throughout the codebase.
  • Simplifies Maintenance: If a bug is found or a change is needed in the duplicated logic, you only have to fix or update it in one place (the extracted procedure) instead of multiple locations.
  • Improves Readability: Code that uses well-named procedures for common tasks is often easier to read and understand than code with repeated blocks.
  • Facilitates Reusability: Creating procedures encourages thinking about how code components can be reused in different parts of the application or even in future projects.

Practical Application

Applying the Rule of Three is a practical step in continuous code improvement.

  1. Identify Duplication: As you write or review code, notice repeated blocks.
  2. First Instance: Write the code as needed.
  3. Second Instance: You might copy and paste it, perhaps with minor modifications. Keep a mental note or make a comment.
  4. Third Instance: Stop! Before copying again, create a new procedure. Move the duplicated logic into this procedure, replacing all instances of the duplicated code with calls to the new procedure.
Instance Number Action Recommended Outcome
1 Write the code Initial implementation
2 Copy and paste is acceptable Temporary duplication tolerated
3 or More Extract into a procedure Code refactored, duplication removed

This rule isn't a strict law but a practical guideline that has proven effective in managing code complexity as software grows.

Related Articles