agentsclimarketplace

Dotnet refactor

Skill CodeMachine0121/DotNet-Developing-Skills/skills/dotnet-refactor

Use when refactoring .NET Core code, reviewing architecture, or checking if code follows James's style in C# projects. Triggers on: private methods, God Class, DI lifetime issues, impure service layer, mutable variables, scattered model conversions, if/switch branch implementations.From its SKILL.md

Install
npx -y skills add CodeMachine0121/DotNet-Developing-Skills --skill dotnet-refactor

Assembled from the repository path, not quoted from the project. Check it against their README if it does not work.

2 things to look at

  • no licenseNo license file was found in the repository. Code published without one is not open source by default, so using it at work is a question for whoever answers licensing questions where you are.
  • 1 stars1 stars. Stars are a popularity signal and not a quality one, but at this level it is likely that nobody has read this closely except its author, and you would be relying on your own review.

SKILL.md

9.9 KB, as published. Nobody here has run it

.NET Core Refactor Style

Rules at a Glance

RuleDescription
No private methodAny occurrence is a violation
No private static methodAny occurrence is a violation
Method <= 5 responsibilitiesCount responsibilities, not lines
Parameters > 2Must extract into a DTO record
Complex pre-conditionsDecorator pattern
Conditional branch implementationsStrategy pattern
Service/Domain layerPure code — no package/framework dependencies
Business logicFluent method chaining
Variable assignmentDeclare and assign in one statement — no deferred assignment
Model conversionsBelong on the source model as To...()

DI Lifetime Rules

Choosing a Lifetime

LifetimeWhen to useNotes
TransientLightweight, stateless servicesCreated on every resolve — higher memory pressure, use sparingly
ScopedState that must persist within a single requestMost common choice; standard for DbContext
SingletonApplication-wide state: config, logging, cachingMemory leaks accumulate over time

Injection Rules (violations)

❌ Never inject Scoped or Transient into a Singleton
   → Effectively promotes the dependency to Singleton lifetime, causing unexpected shared state

❌ Never inject Transient into Scoped
   → Effectively promotes the Transient to Scoped lifetime
// WRONG — Scoped injected into Singleton, Scoped becomes Singleton
public class MySingleton {
    public MySingleton(IScopedService scoped) { ... } // violation
}

// RIGHT — use IServiceScopeFactory to create a scope manually
public class MySingleton {
    private readonly IServiceScopeFactory _factory;
    public MySingleton(IServiceScopeFactory factory) => _factory = factory;

    public async Task DoWork() {
        using var scope = _factory.CreateScope();
        var scoped = scope.ServiceProvider.GetRequiredService<IScopedService>();
        await scoped.Process();
    }
}

Rules in Detail

1. No Private Methods

A private method signals one of two problems: the class is doing too much, or the method is too granular to justify its own name.

// WRONG
public class OrderService {
    public void Process(Order order) { Validate(order); Save(order); }
    private void Validate(Order order) { ... } // violation
}

// RIGHT — if it has independent meaning, extract a class
public class OrderValidator {
    public void Validate(Order order) { ... }
}

// RIGHT — if it's a single expression, inline it
public void Process(Order order) {
    if (!order.IsValid()) throw new ValidationException();
    Save(order);
}

2. No Private Static Methods

private static means the method has no relationship with its containing class.

// WRONG
private static string FormatAddress(Address address) { ... } // violation

// RIGHT — move it into Address
public class Address {
    public string Format() => $"{Street}, {City}";
}

3. Method Has at Most 5 Responsibilities

Count by responsibility or step, not lines. One query = 1, one transformation = 1, one domain call = 1.

// WRONG — seven responsibilities
public async Task<Result> PlaceOrder(CreateOrderDto dto) {
    ValidateDto(dto);              // 1
    var user = GetUser(dto);       // 2
    var products = GetProducts();  // 3
    var discount = CalcDiscount(); // 4
    var order = BuildOrder();      // 5
    await SaveOrder(order);        // 6 ❌
    await SendEmail(order);        // 7 ❌
    return Result.Ok(order);
}

// RIGHT — move validation to a Decorator, core stays <= 5
public async Task<Result> PlaceOrder(CreateOrderDto dto) {
    var user = await _userRepo.Get(dto.UserId);               // 1
    var products = await _productRepo.GetMany(dto.ProductIds); // 2
    var order = BuildOrder(user, products, dto);               // 3
    await _orderRepo.Save(order);                              // 4
    return Result.Ok(order.ToDto());                           // 5
}

4. Parameters > 2 → DTO Record

// WRONG
public Order Build(User user, List<Product> products, Coupon coupon) { ... }

// RIGHT
public record BuildOrderDto(User User, List<Product> Products, Coupon? Coupon);
public Order Build(BuildOrderDto dto) { ... }

5. Complex Pre-conditions → Decorator

Validation, logging, auth, and other cross-cutting concerns belong in a Decorator. The core class stays focused on business logic.

public interface IOrderService {
    Task<Result> PlaceOrder(CreateOrderDto dto);
}

// Core — pure business logic
public class OrderService : IOrderService { ... }

// Decorator — handles validation
public class ValidatedOrderService : IOrderService {
    private readonly IOrderService _inner;
    public ValidatedOrderService(IOrderService inner) => _inner = inner;

    public async Task<Result> PlaceOrder(CreateOrderDto dto) {
        if (!dto.IsValid()) throw new ValidationException(dto.Errors());
        return await _inner.PlaceOrder(dto);
    }
}

DI registration:

services.AddScoped<OrderService>();
services.AddScoped<IOrderService>(sp =>
    new ValidatedOrderService(sp.GetRequiredService<OrderService>()));

6. Conditional Branch Implementations → Strategy

No if/switch to dispatch different implementations. Use Strategy.

// WRONG
public decimal CalcShipping(Order order) {
    if (order.ShippingType == "Express") return order.Total * 0.1m;
    if (order.ShippingType == "Standard") return 15m;
    throw new NotSupportedException();
}

// RIGHT
public interface IShippingStrategy {
    decimal Calculate(Order order);
}
public class ExpressShipping : IShippingStrategy {
    public decimal Calculate(Order order) => order.Total * 0.1m;
}
public class StandardShipping : IShippingStrategy {
    public decimal Calculate(Order order) => 15m;
}

7. Pure Code Layer

Service and Domain layers must not import any packages or frameworks.

// WRONG
using Microsoft.EntityFrameworkCore;
public class OrderService {
    private readonly AppDbContext _db; // violation — direct ORM dependency
}

// RIGHT — isolate behind a Repository interface
public interface IOrderRepository {
    Task<Order> Get(Guid id);
    Task Save(Order order);
}
public class OrderService {
    private readonly IOrderRepository _repo; // pure — depends only on the interface
}

// Repository implementation (framework dependencies allowed here)
public class EfOrderRepository : IOrderRepository {
    private readonly AppDbContext _db;
    ...
}

8. Let the Model Speak (To... conversions)

Model conversions belong on the source model as instance methods.

// WRONG — conversions scattered across the codebase
var dto = new OrderDto { Id = order.Id, Total = order.Total };

// RIGHT
public class Order {
    public OrderDto ToDto() => new(Id, Total, Status.ToString());
    public OrderSummary ToSummary() => new(Id, CreatedAt, Status);
    public OrderCreatedEvent ToCreatedEvent() => new(Id, UserId, Total);
}
var dto = order.ToDto();

9. Fluent Business Logic

// WRONG
var order = new Order();
order.SetUser(user);
order.AddProducts(products);
order.Confirm();

// RIGHT
var order = Order.For(user)
    .WithProducts(products)
    .ApplyCoupon(coupon)
    .Confirm();

10. No Deferred Variable Assignment

Declare and assign in one statement. No declare-then-assign patterns.

// WRONG
decimal total;
if (hasDiscount) total = price * 0.9m;
else total = price;

// RIGHT
var total = hasDiscount ? price * 0.9m : price;

// WRONG
List<Product> available = new();
foreach (var p in products)
    if (p.IsAvailable) available.Add(p);

// RIGHT
var available = products.Where(p => p.IsAvailable).ToList();

// WRONG
string message;
switch (status) {
    case Status.Active: message = "Active"; break;
}

// RIGHT
var message = status switch {
    Status.Active => "Active",
    Status.Inactive => "Inactive",
    _ => throw new NotSupportedException()
};

Refactoring Checklist

  1. Scan for private / private static → resolve all violations first
  2. Count method responsibilities → split any method exceeding 5
  3. Check parameter counts → extract DTO record for anything over 2
  4. Identify complex pre-conditions → extract Decorator
  5. Identify conditional branch implementations → extract Strategy
  6. Verify layer purity → remove illegal using directives
  7. Find model conversions → move to source model as To...()
  8. Apply fluent style to business logic → method chaining
  9. Eliminate deferred assignments → ternary, LINQ, switch expression
  10. Verify DI lifetimes → no lifetime pollution

Violation Quick Reference

SymptomRoot causeFix
private void/T Method()Too much or too little responsibilityExtract class or inline
private static T Method(SomeObj obj)Method belongs to SomeObjMove into SomeObj
Method exceeds 5 responsibilitiesUnclear ownershipSplit method or extract Decorator
3+ parametersParameter clusterExtract DTO record
Large if/else with different implementationsMissing StrategyIStrategy + implementation classes
Service imports framework packagesLayer pollutionExtract IRepository interface
Variable declared then assigned laterMutable mindsetTernary / LINQ / switch expression
Model conversions scattered across codebaseConversions misplacedMove to SourceModel.ToXxx()
Scoped injected into SingletonDI lifetime pollutionUse IServiceScopeFactory
Transient injected into ScopedDI lifetime pollutionAdjust lifetime or redesign

Keep looking

Skills are one crate of 608,475. Ordering is by how many stacks a row turns up in, so the top of any crate is what has actually been picked rather than what has the most stars.