How to refactor code with Gemini CLI — what are the best prompts?
#gen-ai#prompt-engineering
Answer
How to Refactor Code with Gemini CLI
Gemini CLI is a powerful tool for code refactoring because it has direct access to your project files and understands your codebase context through
text
GEMINI.mdSetup for Refactoring
First, create a good
text
GEMINI.mdmarkdown# GEMINI.md ## Project FastAPI backend, Python 3.11, PostgreSQL, SQLAlchemy 2.0 ## Coding Standards - Type hints required on all functions - Docstrings for public functions - Max function length: 30 lines - Use async/await for all I/O - Follow PEP 8
Best Refactoring Prompts
1. Refactor a specific file:
textgemini "Refactor src/auth.py to: - Add type hints to all functions - Extract the JWT logic into a separate JWTService class - Add docstrings to all public methods - Keep the same external interface so no callers break"
2. Extract a function:
textgemini "In src/api/users.py, the create_user endpoint is 80 lines long. Extract the validation logic (lines 15-40) into a separate validate_user_input() function. Keep the function in the same file."
3. Apply a pattern:
textgemini "Refactor all database queries in src/repositories/ to use the Repository pattern. Create a BaseRepository class with common CRUD operations, then have each repository inherit from it. Show me the plan first."
4. Performance refactoring:
textgemini "The process_orders() function in src/orders.py makes N+1 database queries. Refactor it to use a single bulk query with joinedload. Preserve all existing behavior."
5. Large-scale refactoring with planning:
textgemini "I want to add async/await to the entire src/services/ directory. First, show me all functions that need to change and any risks. Then make the changes one file at a time, starting with the simplest."
Refactoring Workflow
bash# Step 1: Give context and get a plan gemini "Review src/payment.py and suggest refactoring improvements. List them by priority." # Step 2: Approve and execute the most important one gemini "Implement refactoring #1 from your previous suggestions: extract PaymentProcessor class" # Step 3: Verify gemini "Run the tests for src/payment.py and check if they all pass" # Step 4: Address any test failures gemini "Test test_payment_timeout is failing. What changed and how to fix it?"
Effective Prompt Patterns
| Pattern | Prompt Template |
|---|---|
| Constraint-preserving | "Refactor X to do Y, keeping the same public API" |
| Step-by-step | "Show me the plan first, then implement step by step" |
| Scope-limited | "Only change the function X, nothing else" |
| Test-first | "After refactoring, check all tests still pass" |
| Explain then do | "Explain what you'll change, then make the changes" |
Common Refactoring Tasks
bash# Add type hints everywhere gemini "Add complete type hints to all functions in src/. Start with the files that have no type hints at all." # Fix code duplication gemini "There's duplicated validation logic in users.py and orders.py. Extract it to a shared utils/validators.py module." # Modernize Python syntax gemini "Update all f-string formatting and replace old % formatting with f-strings throughout the src/ directory." # Improve error handling gemini "Review src/api/ and add proper error handling with specific exception types instead of bare except clauses."
Tips for Better Refactoring Results
- Include relevant files in context: text
gemini @src/auth.py "Refactor the JWT handling" - Specify constraints: "Do not change the public API"
- Ask for impact assessment first: "What would break if I extract this?"
- Review changes before accepting
- Commit before refactoring so you can compare/rollback