Claude Code Plugins

Community-maintained marketplace

Feedback

Refactor C# code - rename types/methods, extract methods/classes, move types between namespaces, simplify complex code, and apply design patterns. Use for code improvements.

Install Skill

1Download skill
2Enable skills in Claude

Open claude.ai/settings/capabilities and find the "Skills" section

3Upload to Claude

Click "Upload skill" and select the downloaded ZIP file

Note: Please verify skill by going through its instructions before using it.

SKILL.md

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 Product to ProductEntity"
  • "Extract this method into a separate class"
  • "Move OrderService to 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:

  1. build skill - Ensure code compiles

    • Must pass before refactoring
    • Establishes clean baseline
  2. test-coverage skill - Ensure tests exist and pass

    • Tests are safety net for refactoring
    • If no tests → Generate them first with dotnet-test-automation
  3. 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
  4. For move operations:

    • namespace-explorer - Check target namespace patterns
    • Ensure consistent with existing structure
  5. 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:

  1. build skill - Verify code still compiles

    • If fails → Invoke build-fixer
    • Must pass before considering refactoring complete
  2. test-coverage skill - Verify tests still pass

    • If fails → Fix tests or revert changes
    • Coverage should not decrease
  3. 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:

  1. ✅ Run build skill to ensure code compiles
  2. ✅ Run test-coverage to ensure tests exist
  3. ✅ Search all references with type-finder
  4. ✅ Check for name collisions with type-collision-detector

During refactoring:

  1. ✅ Update all references atomically
  2. ✅ Maintain file structure conventions
  3. ✅ Preserve XML documentation
  4. ✅ Keep tests aligned

After refactoring:

  1. ✅ Run build to verify compilation
  2. ✅ Run tests to verify behavior unchanged
  3. ✅ Show summary of changes

Refactoring Types

Rename Type

Input:

"Rename Product to ProductEntity"

Process:

  1. Find all occurrences with type-finder
  2. Find all references with Grep
  3. Update:
    • Type definition
    • File name
    • All usages
    • XML comments
    • Test files
  4. 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:

  1. Identify code block to extract
  2. Analyze variables used
  3. Determine parameters and return type
  4. Generate method signature
  5. Replace inline code with method call
  6. 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:

  1. Find type definition
  2. Find all usages
  3. Update namespace in file
  4. Update folder structure (optional)
  5. Update all using statements
  6. 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:

  1. Analyze method with complexity-analyzer
  2. Identify logical sections
  3. Extract each section to method
  4. Replace with method calls
  5. 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:

  1. Identify current implementation
  2. Extract interface
  3. Create strategy classes
  4. Refactor to use strategy
  5. 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