| name | refactor |
| description | Refactor C# code - rename types/methods, extract methods/classes, move types between namespaces, simplify complex code, and apply design patterns. Use for code improvements. |
Refactor Skill
This skill performs safe, comprehensive refactoring operations across your C# codebase.
When to Use This Skill
- "Rename
ProducttoProductEntity" - "Extract this method into a separate class"
- "Move
OrderServiceto a different namespace" - "Simplify this complex method"
- "Apply the Strategy pattern here"
- When code becomes hard to maintain
- After code review suggestions
- During architectural improvements
CRITICAL: Pre-Refactoring Safety Checks
ALWAYS run these checks BEFORE any refactoring:
build skill - Ensure code compiles
- Must pass before refactoring
- Establishes clean baseline
test-coverage skill - Ensure tests exist and pass
- Tests are safety net for refactoring
- If no tests → Generate them first with dotnet-test-automation
For rename operations:
- type-finder - Find all references to the type
- type-collision-detector - Check new name availability
- If collision → Ask user for different name
For move operations:
- namespace-explorer - Check target namespace patterns
- Ensure consistent with existing structure
For simplify complex method:
- complexity-analyzer - Get current complexity score
- Identify which parts to extract
These checks are MANDATORY. Never refactor without them.
CRITICAL: Post-Refactoring Verification
ALWAYS run these after refactoring:
build skill - Verify code still compiles
- If fails → Invoke build-fixer
- Must pass before considering refactoring complete
test-coverage skill - Verify tests still pass
- If fails → Fix tests or revert changes
- Coverage should not decrease
For renames:
- type-finder - Verify old name no longer exists
- Search for any missed references
These verifications are MANDATORY. The refactoring is NOT complete until all checks pass.
API Endpoints
Rename Symbol
POST /transformation/rename
Request:
{
"symbolName": "Product",
"newName": "ProductEntity",
"scope": "solution"
}
Response:
{
"isSuccess": true,
"data": {
"filesModified": 8,
"referencesUpdated": 23
}
}
Extract Method
POST /transformation/extract-method
Request:
{
"documentPath": "src/Services/OrderService.cs",
"startLine": 45,
"endLine": 62,
"methodName": "ValidateOrder"
}
Format Code
POST /transformation/format
Request:
{
"scope": "solution",
"target": "MyProject"
}
How It Works
1. Start the Server
dotnet run --project D:\FractalDataworks\RoslynTools\src\CyberdineDevelopment.RoslynTools.Server
2. Load Solution
using CyberdineDevelopment.RoslynTools.Client;
var client = new RoslynWorkspaceClient("http://localhost:5000");
await client.LoadSolution(@"D:\MyProject\MyProject.sln");
3. Perform Refactoring
// Example: Rename type
var result = await client.RenameSymbol(
symbolName: "Product",
newName: "ProductEntity",
scope: "solution"
);
if (result.IsSuccess)
{
Console.WriteLine($"Modified {result.Data.FilesModified} files");
Console.WriteLine($"Updated {result.Data.ReferencesUpdated} references");
// Get diagnostics to verify no errors
var diagnostics = await client.GetDiagnostics();
if (!diagnostics.Data.Any(d => d.Severity == "Error"))
{
// Commit changes to disk
await client.Commit();
}
}
Semantic Analysis Benefits
Using the Server API provides significant advantages:
- Semantic-Aware Renaming: Uses ISymbol to find all true references, not string matching
- Cross-Project Refactoring: Rename types/methods across entire solution
- Type-Safe Operations: Workspace validates all changes before committing
- Transactional Safety: Roll back if refactoring introduces errors
- Conflict Detection: Detect external file changes before committing
- Symbol Resolution: Understand inheritance, interface implementation, overloads
- Accurate References: Find all references using SymbolFinder, not grep
What This Skill Does
Performs various refactoring operations safely:
1. Rename Refactorings
- Rename types (classes, interfaces, records, structs, enums)
- Rename methods
- Rename properties
- Rename parameters
- Rename variables
- Update all references across solution
2. Extract Refactorings
- Extract method
- Extract class
- Extract interface
- Extract to constant
- Extract to variable
3. Move Refactorings
- Move type to different namespace
- Move type to different file
- Move method to different class
- Reorganize file structure
4. Simplification Refactorings
- Reduce complexity (split complex methods)
- Remove duplication
- Simplify conditionals
- Replace magic numbers with constants
- Convert to LINQ
5. Pattern Application
- Apply Strategy pattern
- Apply Factory pattern
- Apply Repository pattern
- Extract interface for testing
- Apply Dependency Injection
Safety Features
Before refactoring:
- ✅ Run
buildskill to ensure code compiles - ✅ Run
test-coverageto ensure tests exist - ✅ Search all references with type-finder
- ✅ Check for name collisions with type-collision-detector
During refactoring:
- ✅ Update all references atomically
- ✅ Maintain file structure conventions
- ✅ Preserve XML documentation
- ✅ Keep tests aligned
After refactoring:
- ✅ Run
buildto verify compilation - ✅ Run tests to verify behavior unchanged
- ✅ Show summary of changes
Refactoring Types
Rename Type
Input:
"Rename Product to ProductEntity"
Process:
- Find all occurrences with type-finder
- Find all references with Grep
- Update:
- Type definition
- File name
- All usages
- XML comments
- Test files
- Run build to verify
Example:
// Before: Product.cs
namespace MyApp.Domain
{
public class Product { }
}
// After: ProductEntity.cs
namespace MyApp.Domain
{
public class ProductEntity { }
}
// All references updated:
// - var product = new Product() → new ProductEntity()
// - List<Product> → List<ProductEntity>
// - IRepository<Product> → IRepository<ProductEntity>
Extract Method
Input:
"Extract this validation logic into a separate method"
Process:
- Identify code block to extract
- Analyze variables used
- Determine parameters and return type
- Generate method signature
- Replace inline code with method call
- Add method to class
Example:
// Before
public void ProcessOrder(Order order)
{
if (order == null)
throw new ArgumentNullException(nameof(order));
if (order.Items.Count == 0)
throw new InvalidOperationException("Order has no items");
if (order.Total < 0)
throw new InvalidOperationException("Order total cannot be negative");
// ... rest of processing
}
// After
public void ProcessOrder(Order order)
{
ValidateOrder(order);
// ... rest of processing
}
private void ValidateOrder(Order order)
{
if (order == null)
throw new ArgumentNullException(nameof(order));
if (order.Items.Count == 0)
throw new InvalidOperationException("Order has no items");
if (order.Total < 0)
throw new InvalidOperationException("Order total cannot be negative");
}
Move to Namespace
Input:
"Move ProductService from MyApp.Services to MyApp.Domain.Services"
Process:
- Find type definition
- Find all usages
- Update namespace in file
- Update folder structure (optional)
- Update all using statements
- Run build to verify
Example:
// Before: src/Services/ProductService.cs
namespace MyApp.Services
{
public class ProductService { }
}
// After: src/Domain/Services/ProductService.cs
namespace MyApp.Domain.Services
{
public class ProductService { }
}
// All files using it updated:
// using MyApp.Services; → using MyApp.Domain.Services;
Simplify Complex Method
Input:
"Simplify OrderProcessor.ProcessOrder (complexity: 18)"
Process:
- Analyze method with complexity-analyzer
- Identify logical sections
- Extract each section to method
- Replace with method calls
- Verify tests still pass
Example:
// Before: Complexity = 18
public IGenericResult<Order> ProcessOrder(Order order)
{
if (order == null) return Result.Fail("Null order");
if (!ValidateItems(order)) return Result.Fail("Invalid items");
if (!CheckInventory(order)) return Result.Fail("Out of stock");
if (!ProcessPayment(order)) return Result.Fail("Payment failed");
if (!SendConfirmation(order)) return Result.Fail("Email failed");
// ... 50 more lines
}
// After: Complexity = 5 (each extracted method has lower complexity)
public IGenericResult<Order> ProcessOrder(Order order)
{
var validationResult = ValidateOrder(order);
if (!validationResult.Success)
return validationResult;
var inventoryResult = ReserveInventory(order);
if (!inventoryResult.Success)
return inventoryResult;
var paymentResult = ProcessPayment(order);
if (!paymentResult.Success)
return paymentResult;
SendOrderConfirmation(order);
return Result.Ok(order);
}
// Each extracted method now has complexity < 5
Apply Design Pattern
Input:
"Apply Strategy pattern to payment processing"
Process:
- Identify current implementation
- Extract interface
- Create strategy classes
- Refactor to use strategy
- Update dependency injection
Example:
// Before: Hard-coded payment logic
public class OrderService
{
public void ProcessPayment(Order order, string paymentType)
{
if (paymentType == "CreditCard")
{
// Credit card logic
}
else if (paymentType == "PayPal")
{
// PayPal logic
}
// ... more conditionals
}
}
// After: Strategy pattern
public interface IPaymentStrategy
{
IGenericResult<Payment> Process(Order order);
}
public class CreditCardPaymentStrategy : IPaymentStrategy
{
public IGenericResult<Payment> Process(Order order)
{
// Credit card logic
}
}
public class PayPalPaymentStrategy : IPaymentStrategy
{
public IGenericResult<Payment> Process(Order order)
{
// PayPal logic
}
}
public class OrderService
{
private readonly IPaymentStrategy _paymentStrategy;
public OrderService(IPaymentStrategy paymentStrategy)
{
_paymentStrategy = paymentStrategy;
}
public void ProcessPayment(Order order)
{
_paymentStrategy.Process(order);
}
}
Output Format
=== REFACTORING REPORT ===
Operation: Rename type "Product" to "ProductEntity"
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
PRE-REFACTORING CHECKS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ Build status: Success
✅ Tests status: 47 passing
✅ Type found: src/Domain/Models/Product.cs:10
✅ Name available: No collision with "ProductEntity"
Found 23 references across 8 files:
- ProductService.cs: 8 references
- OrderProcessor.cs: 5 references
- ProductRepository.cs: 4 references
- ProductValidator.cs: 3 references
- ProductTests.cs: 3 references
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
APPLYING REFACTORING
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Step 1: Rename type definition
✅ Updated: src/Domain/Models/Product.cs
- Line 10: public class Product → public class ProductEntity
Step 2: Rename file
✅ Renamed: Product.cs → ProductEntity.cs
Step 3: Update references (23 found)
✅ ProductService.cs (8 updates)
- Line 15: List<Product> → List<ProductEntity>
- Line 22: new Product() → new ProductEntity()
- Line 34: IRepository<Product> → IRepository<ProductEntity>
... (5 more)
✅ OrderProcessor.cs (5 updates)
✅ ProductRepository.cs (4 updates)
✅ ProductValidator.cs (3 updates)
✅ ProductTests.cs (3 updates)
Step 4: Update XML documentation
✅ Updated 4 doc comments
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
POST-REFACTORING VERIFICATION
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Running: dotnet build
✅ Build succeeded
Running: dotnet test
✅ All 47 tests passing
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
SUMMARY
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
✅ Refactoring completed successfully
Changes:
- 1 type renamed
- 1 file renamed
- 23 references updated
- 4 doc comments updated
- 8 files modified
Files modified:
✓ src/Domain/Models/ProductEntity.cs (renamed)
✓ src/Services/ProductService.cs
✓ src/Processors/OrderProcessor.cs
✓ src/Repositories/ProductRepository.cs
✓ src/Validators/ProductValidator.cs
✓ tests/ProductTests.cs
(+ 2 more)
Verification:
✓ Build: Success
✓ Tests: 47 passing
✓ No type collisions
✓ All references updated
Common Refactoring Patterns
1. Reduce Method Complexity
If complexity > 15:
1. Split into smaller methods
2. Extract validation logic
3. Extract business rules
4. Extract external calls
2. Remove Code Duplication
If same code in 3+ places:
1. Extract to shared method
2. Consider creating utility class
3. Or apply Template Method pattern
3. Improve Naming
If name unclear:
1. Rename to be more descriptive
2. Follow domain language
3. Match naming conventions
4. Separate Concerns
If class does multiple things:
1. Extract each responsibility to class
2. Apply Single Responsibility Principle
3. Use composition
Integration with Other Skills
Full refactoring workflow:
1. complexity-analyzer → Identify what needs refactoring
2. type-collision-detector → Check name availability
3. build → Ensure starting from clean state
4. refactor → Apply refactoring
5. build → Verify still compiles
6. test-coverage → Verify tests still pass
7. project-health → Check overall health
Safe rename workflow:
1. type-finder "OldName" → Find current definition
2. type-collision-detector → Check "NewName" available
3. refactor → Rename OldName to NewName
4. build → Verify success
Extract interface for testing:
1. refactor → Extract interface from concrete class
2. Update DI configuration
3. Generate tests with mocks
4. test-coverage → Verify coverage
Advanced Features
Preserve Git History
Use git mv when renaming files to preserve history
Update Test Files
Automatically update test file names and test class names
ProductTests → ProductEntityTests
Namespace Alignment
Ensure namespace matches folder structure:
src/Domain/Services → namespace MyApp.Domain.Services
Format After Refactoring
Run code formatter on modified files
Refactoring Checklist
Before refactoring:
- Code compiles
- Tests pass
- Changes committed (so you can revert)
- Target name available (no collisions)
During refactoring:
- Update type definition
- Update all references
- Update file names
- Update XML docs
- Update tests
After refactoring:
- Build succeeds
- All tests pass
- No new warnings
- Code review if needed
Notes
- Uses Roslyn Workspace API with full semantic model
- Semantic-aware refactoring (uses ISymbol, not string matching)
- Always validates before and after with in-memory compilation
- Transaction-safe with rollback capability
- Can detect conflicts with external file changes
- Tracks all changes made in workspace
- Automatic conflict resolution with three-way merge
- Respects .editorconfig settings
- Cross-project refactoring support
- Server maintains workspace state throughout refactoring session