正在学习

10.3 Incremental Refactoring and Documentation

After refactoring

import hashlib

import sqlite3

from typing import Optional

class DatabaseHelper:

"""Utility class for database interactions."""

def __init__(self, db_path: str):

    self.db_path = db_path

def execute_query(self, query: str, params: tuple = ()) -> Optional[list]:

    """Execute query and return fetched results if available."""

    with sqlite3.connect(self.db_path) as conn:

        cur = conn.cursor()

        cur.execute(query, params)

        if query.strip().lower().startswith("select"):

            return cur.fetchall()

        conn.commit()

    return None

class AuthManager:

"""Handles user registration and login authentication."""

def __init__(self, db_helper: DatabaseHelper):

    self.db = db_helper

def _hash_password(self, password: str) -> str:

    """Hash the password using SHA-256."""

    return hashlib.sha256(password.encode()).hexdigest()

def register_user(self, username: str, password: str):

    """Register new users by saving hashed passwords."""

    hashed = self._hash_password(password)

    self.db.execute_query(

        "INSERT INTO users (username, password) VALUES (?, ?)",

        (username, hashed)

    )

def login(self, username: str, password: str) -> bool:

    """Validate user credentials against stored hashes."""

    result = self.db.execute_query(

        "SELECT password FROM users WHERE username=?", (username,)

    )

    if not result:

        return False

    stored_hash = result[0][0]

    return stored_hash == self._hash_password(password)

This refactor introduces a single-responsibility design while retaining identical functionality. Claude also adds docstrings and improves readability — demonstrating incremental improvement without breaking compatibility.

You could then extend this prompt with:

“Claude, generate unit tests for bothDatabaseHelper andAuthManager to verify behavior after refactoring.”

Claude would return a full, runnable test suite usingpytest that validates the refactor before committing.

Clarification Table: Refactoring Workflow Summary

Step Goal Claude’s Role Developer Action
1. Define Scope Identify one class or function to refactor Understands purpose, dependencies Provide clear context
2. Generate Refactor Rewrite logic without changing behavior Produces optimized and documented code Review and test output
3. Validate Confirm old and new versions behave the same Writes or checks unit tests Run tests locally
4. Document Explain what changed and why Adds docstrings and changelog text Commit and push
5. Iterate Move to next component Maintains continuity in style Repeat with new module

Incremental refactoring with Claude Code provides a safe, structured path to modernizing large projects. Instead of high-risk rewrites, developers can evolve their systems through steady, validated improvements. The inclusion of self-documenting features — like docstrings and changelogs — ensures long-term maintainability and clarity.

By embracing small, Claude-assisted iterations, teams gain confidence that every change strengthens their codebase without disrupting stability. In the next section, we’ll build upon this approach to explore multi-file consistency and documentation alignment, ensuring that as your code evolves, your architecture and written documentation evolve right alongside it.

10.4 Maintaining Consistency Across Multiple Prompts

When working with Claude Code on large projects, developers often break their interactions into multiple prompts — one for each module, feature, or debugging session. However, as projects grow, maintaining consistency across these prompts becomes a key challenge. Without continuity, Claude might make style changes that drift from the team’s standards, rename variables differently, or interpret prior context inconsistently.

Claude’s conversational intelligence can maintain context within a session, but developers must still manage prompt consistency manually when working across multiple sessions or team members. In this section, we’ll explore how to maintain a coherent tone, structure, and coding standard across all interactions with Claude. You’ll learn techniques to establish persistent context, enforce style rules, and keep Claude “on the same page” as your team throughout long-running projects.

Concept Development

Claude doesn’t store long-term memory between separate prompts; it only uses the context you provide. That means maintaining consistency requires deliberate prompt engineering strategies and a disciplined workflow. Here are three foundational principles for achieving that:

  1. Persistent Context Sharing — Keep a lightweight “Claude Context File” (e.g., claude_context.md) that summarizes coding conventions, architecture, and project goals. You can paste this at the start of each new Claude session to reestablish alignment.
  2. Style and Tone Anchoring — Define specific conventions once and reuse them consistently. This includes naming standards, docstring formats, test patterns, and file structures. Claude can follow these rules exactly if they’re restated each time.
  3. Incremental Session Linking — When a task spans multiple prompts, remind Claude of what was previously done. For example: “Here’s the class you helped refactor earlier — now let’s add unit tests to it.” This prevents Claude from drifting in its assumptions about code intent or dependencies.

Together, these techniques ensure that each interaction — no matter how isolated — contributes to a unified, predictable project output.

Hands-On Example: Using a Shared Context File

Imagine you’re developing a FastAPI-based internal service with multiple engineers using Claude for different modules. Without a shared context, each developer’s prompts might result in inconsistent structure. To fix this, you create a central context file named claude_context.md that defines the project’s expectations.


练习题

What is the primary purpose of the DatabaseHelper class?

A. To handle user authentication
B. To manage database interactions
C. To hash passwords
D. To execute SQL queries directly

In the DatabaseHelper class, what does the execute_query method return for SELECT queries?

A. None
B. The number of affected rows
C. A list of fetched results
D. A boolean indicating success

What is the purpose of the AuthManager class?

A. To manage database connections
B. To handle user registration and login authentication
C. To execute SQL queries
D. To hash passwords for storage

How does the _hash_password method in the AuthManager class hash passwords?

A. Using MD5
B. Using SHA-1
C. Using SHA-256
D. Using bcrypt

Which of the following are true about the register_user method in the AuthManager class? (Select all that apply)

A. It saves plain text passwords to the database
B. It hashes passwords before saving them
C. It uses the DatabaseHelper class to execute queries
D. It requires a username and password as parameters

Which steps are part of the refactoring workflow? (Select all that apply)

A. Define Scope
B. Generate Refactor
C. Validate
D. Document
E. Iterate
F. Deploy

The login method in the AuthManager class returns True if the provided password matches the stored hash.

The DatabaseHelper class commits changes to the database for all types of queries.

The _____ method in the AuthManager class is responsible for hashing passwords using SHA-256.

The _____ class is used by the AuthManager class to interact with the database.

Explain the purpose of the execute_query method in the DatabaseHelper class.

Describe the process of validating user credentials in the login method of the AuthManager class.

Which principles help maintain consistency across multiple prompts? (Select all that apply)

A. Persistent Context Sharing
B. Style and Tone Anchoring
C. Incremental Session Linking
D. Direct Code Execution
E. Automated Testing

The DatabaseHelper class is designed to handle only SELECT queries.

What is the benefit of separating database operations from authentication logic in the refactored code?

What is the main purpose of the DatabaseHelper class in the refactored code?

A. To handle user registration and login authentication
B. To provide a utility for database interactions
C. To hash passwords using SHA-256
D. To execute only SELECT queries

Which of the following steps are part of the refactoring workflow described in the text? (Select all that apply)

A. Define Scope
B. Generate Refactor
C. Validate
D. Document
E. Deploy
F. Iterate

The AuthManager class in the refactored code is responsible for both hashing passwords and executing database queries.

The __________ method in the AuthManager class is used to hash passwords using SHA-256 before storing them in the database.

Explain how the execute_query method in the DatabaseHelper class contributes to the separation of concerns in the refactored code.

登录后解锁笔记、知识点解析、AI 问答

立即登录