Skip to main content

Overview

Refactron provides intelligent refactoring suggestions with safety previews, risk scoring, and automated fixes. All refactorings include backup and rollback capabilities.

Basic Refactoring

Preview Changes

Always preview refactoring suggestions before applying:
refactron refactor myfile.py --preview

Apply Refactoring

Apply all suggested refactorings:
refactron refactor myfile.py
Refactoring modifies your code. Always preview changes first and ensure you have backups or version control.

Available Refactorers

Replaces magic numbers with named constants
# Before
def calculate_tax(amount):
    return amount * 0.18

# After
TAX_RATE = 0.18

def calculate_tax(amount):
    return amount * TAX_RATE
Adds missing docstrings to functions and classes
# Before
def calculate_total(items):
    return sum(item.price for item in items)

# After
def calculate_total(items):
    """Calculate total price for list of items.
    
    Args:
        items: List of items with price attribute
        
    Returns:
        Total sum of item prices
    """
    return sum(item.price for item in items)
Refactors complex conditional expressions
# Before
if not (x < 10 or x > 20):
    process()

# After
if 10 <= x <= 20:
    process()
Reduces function parameters using dataclasses or dicts
# Before
def create_user(name, email, age, city, country):
    pass

# After
from dataclasses import dataclass

@dataclass
class UserData:
    name: str
    email: str
    age: int
    city: str
    country: str

def create_user(user: UserData):
    pass

Risk Levels

Refactoring suggestions include risk scores:

Safe (0.0)

Formatting, imports only

Low (0.1-0.2)

Documentation, constants

Moderate (0.3-0.5)

Logic changes

High (0.6-1.0)

Complex transformations

Filter by Risk Level

# Only apply safe refactorings
refactron refactor myfile.py --risk-level safe

# Apply safe and low-risk refactorings
refactron refactor myfile.py --risk-level low

Specific Refactorings

Apply only specific types of refactoring:
# Only extract constants
refactron refactor myfile.py --type extract_constant

# Multiple types
refactron refactor myfile.py --type extract_constant --type add_docstring

Python API

from refactron import Refactron

refactron = Refactron()

# Preview refactoring
result = refactron.refactor("myfile.py", preview=True)
result.show_diff()

# Apply specific refactorings
result = refactron.refactor(
    "myfile.py",
    preview=False,
    operation_types=["extract_constant", "add_docstring"]
)

if result.success:
    print(f"Applied {len(result.operations)} refactorings")
    print(f"Backup: {result.backup_path}")

Auto-Fix

The autofix command applies safe, automated fixes:
# Preview auto-fixes
refactron autofix myfile.py --preview

# Apply auto-fixes
refactron autofix myfile.py --apply
Auto-fix includes 14 automated fixers for common issues.

Backup and Rollback

Every refactoring creates automatic backups:

List Rollback Sessions

refactron rollback --list

Rollback Specific Session

refactron rollback --session <session-id>

Python API Rollback

from refactron.autofix.file_ops import FileOperations

file_ops = FileOperations()

# Rollback one file
file_ops.rollback_file("myfile.py")

# Rollback all changes
file_ops.rollback_all()

Refactoring Workflow

1

Analyze

First, analyze your code to identify issues
refactron analyze myproject/
2

Preview

Preview refactoring suggestions
refactron refactor myproject/ --preview
3

Review

Review the diff output and risk scores
4

Apply

Apply refactorings you want to keep
refactron refactor myproject/ --type extract_constant
5

Test

Run your tests to ensure nothing broke
6

Rollback (if needed)

Rollback if something went wrong
refactron rollback --session <id>

Configuration

Configure refactoring behavior in .refactron.yaml:
.refactron.yaml
# Enable specific refactorers
enabled_refactorers:
  - extract_constant
  - add_docstring
  - simplify_conditionals
  - reduce_parameters

# Risk tolerance
max_risk_score: 0.5  # Don't apply refactorings with risk > 0.5

# Backup settings
create_backups: true
backup_dir: .refactron/backups

Pattern Learning Integration

Refactron learns from your refactoring decisions:
# Refactor with pattern learning
refactron refactor myfile.py --feedback

# Provide explicit feedback
refactron feedback <operation-id> --action accepted
Learn more about pattern learning in the Pattern Learning Guide

Best Practices

Use --preview to see changes before applying them
Commit your code before refactoring for easy rollback
Run your test suite after applying refactorings
Begin with safe refactorings, then gradually increase risk tolerance
Refactor small portions at a time rather than entire codebase

Next Steps