### Preview refactoring-kit Installation Source: https://github.com/bienhoang/refactoring-kit/blob/main/README.md Use the --dry-run flag to preview what files would be installed without actually performing the installation. ```bash npx refactoring-kit install --tool=cursor --dry-run ``` -------------------------------- ### Neovim Plugin Setup Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/lua.md Standard entry point for Neovim plugins using the setup pattern. ```lua require("plugin").setup(opts) ``` -------------------------------- ### Project Configuration Example Source: https://context7.com/bienhoang/refactoring-kit/llms.txt An example of a `.refactoring.yaml` configuration file, demonstrating how to customize analysis thresholds and workflow behavior. ```yaml # .refactoring.yaml - all fields optional # Analysis thresholds (override defaults) thresholds: max_method_lines: 30 # default: 20 max_class_lines: 300 # default: 250 max_file_lines: 600 # default: 500 max_parameters: 4 # default: 5 max_cyclomatic_complexity: 12 # default: 10 max_cognitive_complexity: 15 # default: 10 ``` -------------------------------- ### Install Refactoring Kit CLI Source: https://context7.com/bienhoang/refactoring-kit/llms.txt Install the refactoring-kit CLI globally or for specific AI tools. Use --tool to specify tools and --global for global installation. Preview changes with --dry-run. ```bash # Install globally for Claude Code (default) npm install -g refactoring-kit ``` ```bash # Install for specific tools npx refactoring-kit install --tool=cursor npx refactoring-kit install --tool=windsurf,copilot npx refactoring-kit install --tool=cursor --global ``` ```bash # Preview installation without writing files npx refactoring-kit install --tool=cursor --dry-run ``` -------------------------------- ### Install refactoring-kit for a Project Source: https://github.com/bienhoang/refactoring-kit/blob/main/README.md Install the refactoring-kit as a development dependency for a specific project. ```bash npm install --save-dev refactoring-kit ``` -------------------------------- ### Install Command - Commander CLI Source: https://github.com/bienhoang/refactoring-kit/blob/main/docs/code-standards.md Installs refactoring kit skills for specified tools. Use --global for global installation and --dry-run to preview changes without writing files. ```bash refactoring-kit install [--tool=] [--global] [--dry-run] ``` -------------------------------- ### Vue Composition API with ` ``` -------------------------------- ### Install refactoring-kit for Specific Tools Source: https://github.com/bienhoang/refactoring-kit/blob/main/README.md Install the refactoring-kit for specific AI tools using the CLI. You can install for multiple tools at once or globally. ```bash npx refactoring-kit install --tool=cursor ``` ```bash npx refactoring-kit install --tool=windsurf,copilot ``` ```bash npx refactoring-kit install --tool=cursor --global ``` -------------------------------- ### Moq Mocking Example Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/csharp.md Demonstrates creating a mock object for a service using the popular Moq library. ```csharp Mock() ``` -------------------------------- ### Refactoring Plan Structure Example Source: https://context7.com/bienhoang/refactoring-kit/llms.txt Illustrates the typical directory structure and file organization for generated refactoring plans. ```bash # Generated plan structure: # plans/refactor-services/ # ↓ reports/ # → analysis-report.md # ↓ plan.md # Main plan with YAML frontmatter # ↓ phase-01-extract-god-class.md # ↓ phase-02-reduce-duplication.md # ↓ phase-03-improve-naming.md ``` -------------------------------- ### Manual Project-level Installation (Claude Code) Source: https://github.com/bienhoang/refactoring-kit/blob/main/README.md Manually clone the refactoring-kit repository into the project directory for project-level use with Claude Code. ```bash git clone https://github.com/bienhoang/refactoring-kit.git .claude/skills/refactoring ``` -------------------------------- ### Manual Global Installation (Claude Code) Source: https://github.com/bienhoang/refactoring-kit/blob/main/README.md Manually clone the refactoring-kit repository for global use with Claude Code. ```bash git clone https://github.com/bienhoang/refactoring-kit.git ~/.claude/skills/refactoring ``` -------------------------------- ### Mermaid Dependency Graph Example Source: https://github.com/bienhoang/refactoring-kit/blob/main/resources/templates/report-template.md Example of a dependency graph using Mermaid syntax. Useful for visualizing module relationships in multi-file targets. ```mermaid graph LR A[ModuleA] --> B[ModuleB] B --> C[ModuleC] ``` -------------------------------- ### Install Husky and Lint-Staged Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/ci-integration.md Commands to install husky and lint-staged for managing pre-commit hooks in JavaScript/TypeScript projects. ```bash # Install husky + lint-staged (JS/TS projects) npx husky init npm install --save-dev lint-staged ``` -------------------------------- ### Proper Metatable Setup Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/lua.md Implement correct object-oriented patterns using `setmetatable` with `__index` pointing to the metatable itself for class-like behavior. ```lua local MyClass = {} MyClass.__index = MyClass local instance = setmetatable({}, MyClass) function instance:method() print("Hello from instance!") end ``` -------------------------------- ### Install Refactoring Kit Source: https://github.com/bienhoang/refactoring-kit/blob/main/README.md Install the refactoring-kit globally or explicitly for specific tools. The default adapter is Claude Code, installed via an npm postinstall hook. ```bash npm install -g refactoring-kit ``` ```bash npx refactoring-kit install --tool=cursor,windsurf ``` -------------------------------- ### Aligned Refactoring Output Example Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/lua.md Example format for reporting aligned refactorings, including smell name, location, code snippets, and rationale. ```text **[Smell Name]** in {file}:{line} Current: {code snippet} Suggested: {refactored code} Rationale: {why this is better, referencing detected conventions} ``` -------------------------------- ### Output Format: Convention Improvements Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/cpp.md Example format for suggesting optional convention improvements, detailing the current and suggested conventions and providing a before-and-after example. ```text Your project uses {current convention}. Consider {suggested convention} because {reasoning}. Example: {before → after} ``` -------------------------------- ### shunit2 Test Example Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/shell-bash.md An example of a test case using the shunit2 xUnit-style testing framework. It defines a test function and uses assertion methods like `assertEquals`. ```shell testMyFunc() { result=$(my_func) assertEquals "expected" "$result" } ``` -------------------------------- ### Layered (N-Tier) Directory Heuristics Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/architecture/architectural-styles.md Example directory structure for the Layered (N-Tier) architectural style, indicating common subdirectories for controllers, services, repositories, and models. ```bash src/ ├── controllers/ | presentation/ | routes/ | api/ | handlers/ ├── services/ | business/ | logic/ | usecases/ ├── repositories/ | persistence/ | dal/ | dao/ └── models/ | entities/ | database/ | schema/ ``` -------------------------------- ### Serverless Directory Structure Example Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/architecture/architectural-styles.md Illustrates a typical directory layout for a Serverless / FaaS project, emphasizing function-centric organization and shared code layers. ```tree src/ ├── functions/ | lambdas/ | handlers/ │ ├── http-handler.ts │ ├── event-handler.ts │ └── scheduled-job.ts ├── shared/ | layers/ | utils/ └── infrastructure/ | iac/ └── serverless.yml | sam.yaml | template.yaml ``` -------------------------------- ### Install refactoring-kit Globally Source: https://github.com/bienhoang/refactoring-kit/blob/main/README.md Install the refactoring-kit globally to make it available in all projects. This is the default for Claude Code. ```bash npm install -g refactoring-kit ``` -------------------------------- ### Hexagonal (Ports & Adapters) Directory Heuristics Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/architecture/architectural-styles.md Example directory structure for the Hexagonal (Ports & Adapters) architectural style, showing typical organization for domain, ports, and adapters. ```bash src/ ├── domain/ | core/ ├── ports/ | interfaces/ │ ├── in/ | inbound/ | driving/ │ └── out/ | outbound/ | driven/ ├── adapters/ | infrastructure/ │ ├── in/ | web/ | http/ | grpc/ │ └── out/ | persistence/ | clients/ └── config/ | di/ | wiring/ ``` -------------------------------- ### Output Format: Aligned Refactorings Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/cpp.md Example format for presenting refactoring suggestions, including the detected smell, file location, current code, suggested code, and rationale. ```text **[Smell Name]** in `{file}:{line}` Current: {code snippet} Suggested: {refactored code} Rationale: {why this is better, referencing detected conventions} ``` -------------------------------- ### Qt Event Loop Execution Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/cpp.md Start the Qt event loop using `QCoreApplication::exec()` to enable event-driven processing in Qt applications. ```cpp QCoreApplication::exec() ``` -------------------------------- ### Bats Test Example Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/shell-bash.md An example of a test case using the Bats (Bash Automated Testing System) framework. It demonstrates running a function and asserting its success and output. ```shell @test "description" { run my_func assert_success assert_output "expected" } ``` -------------------------------- ### Start SimpleCov for Code Coverage Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/ruby.md Integrate SimpleCov into your test suite to measure code coverage. Ensure `SimpleCov.start` is called early in your spec helper. ```ruby # spec/spec_helper.rb require 'simplecov' SimpleCov.start 'rails' # ... other RSpec configurations ``` -------------------------------- ### xUnit Testing Command Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/csharp.md Execute tests using xUnit, the preferred framework, with the 'dotnet test' command. It supports modern, parallel execution and constructor injection for setup. ```bash dotnet test ``` -------------------------------- ### Clean Architecture Directory Heuristics Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/architecture/architectural-styles.md Example directory structure for the Clean Architecture style, illustrating the concentric circle organization with directories for entities, use cases, interface adapters, and frameworks. ```bash src/ ├── entities/ | domain/ ├── usecases/ | application/ | interactors/ ├── interface_adapters/ | adapters/ | presentation/ └── frameworks/ | infrastructure/ | drivers/ ``` -------------------------------- ### Package Boundary Rules Example Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/dependency-analysis.md Illustrates allowed and forbidden dependency directions between different types of code modules (e.g., feature, core, shared, api, service, repository). Helps enforce architectural integrity. ```text Allowed: feature → core feature → shared/utils api → service → repository Forbidden: core → feature (core must not know about features) feature-A → feature-B (features should be independent) repository → api (lower layer must not import higher) ``` -------------------------------- ### Wallaby: Browser Interaction Example Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/elixir.md Demonstrates basic browser interaction using Wallaby for end-to-end testing. Includes visiting a page and filling in a form field. ```elixir visit("/login") |> fill_in(Query.text_field("Email"), with: "test@example.com") ``` -------------------------------- ### Standalone Mode User Prompt Source: https://context7.com/bienhoang/refactoring-kit/llms.txt Example of the interactive prompt shown when using `/refactor:implement` in standalone mode (Mode B), detailing detected smells and proposed transformations. ```markdown # Standalone mode prompts user: # "Smells found: 5 (1 critical, 3 major, 1 minor) # Proposed transformations: # 1. Extract Method for calculateTotal (Long Method) # 2. Move Method for validateUser (Feature Envy) # Options: [Apply all] [Select which to apply] [Cancel]" ``` -------------------------------- ### Detection Checklist for Architectural Smells Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/architecture/architectural-smells.md A step-by-step guide for systematically detecting architectural smells in a project. It covers module dependencies, structural smells, boundary smells, and distribution smells. ```bash Step 1: Build Module Dependency Graph - Parse imports/requires across all modules - Calculate per-module: incoming edges, outgoing edges, total edges - Result: adjacency list + edge counts Step 2: Check Structural Smells □ God Module: any module with >30% of incoming edges? □ Hub Dependency: any module with >40% of total edges? □ Ambiguous Boundaries: any module exporting 3+ domain concepts? □ Feature Scattering: recent features touching 5+ modules? Step 3: Check Boundary Smells □ Layer Violations: any imports against style's dependency flow? □ Cyclic Dependencies: any cycles in dependency graph? □ Missing Abstraction: infrastructure imports in domain/service modules? □ Leaky Abstraction: infrastructure types in public APIs? Step 4: Check Distribution Smells (distributed styles only) □ Distributed Monolith: cross-service code imports or lockstep deploys? □ Shared Database: multiple services sharing DB tables? □ Chatty Services: >10 cross-service calls per operation? □ Nano-services: services with <100 LOC business logic? Step 5: Score and Prioritize - Assign severity per finding (critical/major/minor) - Score using ROI formula from references/prioritization.md - Group into tiers: Quick Win, Strategic, Planned ``` -------------------------------- ### Minimal Refactoring Configuration Source: https://github.com/bienhoang/refactoring-kit/blob/main/README.md A minimal example of a `.refactoring.yaml` configuration file to customize behavior, such as setting code quality thresholds and ignoring specific files or directories. ```yaml # .refactoring.yaml thresholds: max_method_lines: 30 max_cyclomatic_complexity: 12 ignore: - "**/generated/**" - "**/migrations/**" ``` -------------------------------- ### Mockito-Scala Mocking Example Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/scala.md Shows how to create a mock object for a trait using Mockito-Scala. This is useful for isolating components during testing. ```scala when(mock.method()).thenReturn(value) ``` -------------------------------- ### Floki: HTML Parsing for Testing Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/elixir.md An example of using Floki for parsing HTML content, typically used in testing to assert on rendered output. ```elixir Floki.parse_document(html_content, :html) |> Floki.filter("h1") ``` -------------------------------- ### Create Temporary Directory for Test Isolation Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/shell-bash.md Use `mktemp -d` in test setup to create a unique temporary directory for test isolation, and ensure it's removed in teardown using `rm -rf`. ```shell mktemp -d ``` -------------------------------- ### ASP.NET Core Minimal API Endpoint Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/csharp.md Define simple HTTP endpoints using Minimal APIs in ASP.NET Core for streamlined web application development. This example shows a basic GET endpoint. ```csharp app.MapGet("/hello", () => "Hello World!"); ``` -------------------------------- ### Dart Unit Test Example Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/dart.md Write unit tests for Dart code using the 'test' package. Use expect() for assertions. Run tests with 'dart test'. ```dart test('description', () { expect(result, equals(expected)); }) ``` -------------------------------- ### Replace Raw Loops with std::find Algorithm Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/cpp.md Avoid manual loops for common operations like searching. Use algorithms from `` for more concise and less error-prone code. This example shows replacing a manual loop with `std::find`. ```cpp auto it = std::find(v.begin(), v.end(), x); ``` -------------------------------- ### Example: Rule of Three for Pattern Application Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/design-patterns.md Illustrates the 'Rule of Three' principle for introducing design patterns. Avoid premature abstraction; introduce a pattern only when a problem manifests in at least three distinct places. ```text Example: A function has an if/else for two payment types (credit card, PayPal). Don't introduce Strategy — a simple conditional is clearer. When a third type arrives (crypto), now extract a Strategy interface. The second case confirms the pattern; the third justifies the abstraction. ``` -------------------------------- ### Qt Test Framework QTEST_MAIN Macro Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/cpp.md Use the `QTEST_MAIN()` macro to set up the entry point for tests written with the Qt Test framework. ```cpp QTEST_MAIN() ``` -------------------------------- ### Graceful Shutdown (Gin/Echo/Fiber) Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/go.md Implement graceful shutdown by handling `os.Signal` and using `context` with a timeout to allow ongoing requests to complete before exiting. ```go quit := make(chan os.Signal, 1) signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) <-quit ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() if err := srv.Shutdown(ctx); err != nil { log.Fatal("Server forced to shutdown:", err) } ``` -------------------------------- ### Mutable Public Fields Fix Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/csharp.md Avoid using public fields for data encapsulation. Instead, use properties with appropriate accessors (`get; set;`, `get; init;`, or `get; private set;`) to control access and enable change notification. ```csharp // Smell: public string Name; public int Count; // Fix: public string Name { get; set; } public int Count { get; private set; } ``` -------------------------------- ### Circuit Breaker Configuration Example Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/architecture/architectural-patterns.md Configure circuit breaker parameters such as failure rate threshold, slow call threshold, wait duration, and minimum calls required for evaluation. Use when external services may fail or become slow. ```yaml failure_rate_threshold: 50% slow_call_threshold: 60% wait_duration: 30s minimum_calls: 10 ``` -------------------------------- ### shellspec Test Example Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/shell-bash.md An example of a test case using the shellspec BDD (Behavior-Driven Development) testing framework. It shows how to describe a function, its behavior, and expected outcomes. ```shell Describe 'func' It 'works' When call func The output should eq "x" End End ``` -------------------------------- ### Go Test Coverage Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/go.md Generate and view Go test coverage reports. First, create a coverage profile, then open it in a browser. ```bash go test -coverprofile=coverage.out ./... ``` ```bash go tool cover -html=coverage.out ``` -------------------------------- ### FluentAssertions Assertion Example Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/csharp.md Utilize FluentAssertions for expressive assertions in tests, comparing results against expected values. ```csharp result.Should().BeEquivalentTo(expected) ``` -------------------------------- ### Default Test Framework Suggestion Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/csharp.md If no test framework is detected, suggest xUnit as the default choice. ```csharp xUnit ``` -------------------------------- ### List Supported Tools Source: https://context7.com/bienhoang/refactoring-kit/llms.txt List all supported AI coding tools and their capabilities. This command helps identify which tools are compatible with the refactoring kit. ```bash # List all 14 supported tools with capabilities npx refactoring-kit tools # Output: # Supported tools (14): # claude-code Claude Code [commands, refs, workflows] # cursor Cursor [refs, globs] # windsurf Windsurf [refs, globs] # copilot GitHub Copilot [refs] # roo-code Roo Code [workflows] # ... ``` -------------------------------- ### ScalaCheck Property Test Example Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/scala.md Demonstrates a property-based test using ScalaCheck. This is recommended for testing parsers, serializers, and mathematical functions. ```scala forAll { (s: String) => s.reverse.reverse == s } ``` -------------------------------- ### Phoenix LiveView: Use `assign_new/3` for Initial Mount Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/elixir.md Utilize `assign_new/3` in LiveView for expensive computations that are only required during the initial mount of the component. ```elixir assign_new(socket, :expensive_data, fn -> compute_expensive_data() end) ``` -------------------------------- ### PHPUnit Test Execution Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/php.md Execute PHPUnit tests using the vendor binary. Ensure your project's dependencies are installed via Composer. ```bash vendor/bin/phpunit ``` -------------------------------- ### PHP Version Constraint Example Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/php.md Read the PHP version constraint from composer.json to gate language features like enums and match expressions. ```json { "require": { "php": ">=8.1" } } ``` -------------------------------- ### Use Shared Examples in RSpec Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/ruby.md Extract common test behavior into `shared_examples` in RSpec to avoid repetition and promote consistency across tests. ```ruby shared_examples 'votable' do it 'calculates score correctly' it 'has many votes' end describe Post it_behaves_like 'votable' end ``` -------------------------------- ### Perform Static Analysis in Go Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/dependency-analysis.md Utilize the built-in `go vet` command for static analysis of your Go project, which includes checking for import issues. Run this command from your project's root. ```bash go vet ./... ``` -------------------------------- ### StreamData: Property-Based Testing Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/elixir.md An example of property-based testing with StreamData. Define data generators and assertions to test properties that should hold true for various inputs. ```elixir check all data <- binary() do assert is_binary(data) end ``` -------------------------------- ### Use mktemp for Temporary Files Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/shell-bash.md Avoid predictable temporary file names like `/tmp/myapp.$$`. Use `mktemp` to create secure temporary files and `trap` to ensure cleanup. ```shell echo > /tmp/app.$$ ``` ```shell tmpfile=$(mktemp); trap 'rm -f "$tmpfile"' EXIT ``` -------------------------------- ### Null-Conditional and Null-Coalescing Operators Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/csharp.md Simplify null checks and provide default values using the null-conditional (`?.`) and null-coalescing (`??`) operators. This example demonstrates their combined usage. ```csharp var name = user?.Profile?.Name ?? "Guest"; ``` -------------------------------- ### C# 10 File-Scoped Namespaces Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/csharp.md Use file-scoped namespaces for a more compact code structure, eliminating the need for nested braces. This example demonstrates the syntax. ```csharp namespace MyApp; // Code here ``` -------------------------------- ### LuaUnit Testing Framework Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/lua.md xUnit-style testing with LuaUnit, including test methods and running the suite. ```lua function TestMod:test_add() lu.assertEquals(add(2,3), 5) end; os.exit(lu.LuaUnit.run()) ``` -------------------------------- ### Git Stash Uncommitted Changes Source: https://github.com/bienhoang/refactoring-kit/blob/main/REFERENCE.md Suggest stashing uncommitted changes, including untracked files, before starting a refactoring process. This command saves your work-in-progress. ```bash git stash --include-untracked ``` -------------------------------- ### Quarkus Test with REST Assured Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/java.md Use @QuarkusTest with REST Assured for efficient endpoint testing in Quarkus applications. This setup is optimized for testing RESTful services. ```java import io.quarkus.test.junit.QuarkusTest; import io.restassured.RestAssured; import org.junit.jupiter.api.Test; @QuarkusTest class EndpointTest { @Test void testHelloEndpoint() { RestAssured.given() .when().get("/hello") .then() .statusCode(200) .body("content", equalTo("Hello RESTEasy")); } } ``` -------------------------------- ### HTTP Handler Testing with httptest Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/go.md Use `httptest` package for testing HTTP handlers in Go. Provides `NewRecorder` for responses and `NewServer` for testing servers. ```go httptest.NewRecorder() ``` ```go httptest.NewServer() ``` -------------------------------- ### String Interpolation Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/csharp.md Use interpolated strings (`$"..."`) for cleaner and more readable string formatting compared to `string.Format`. This example shows the basic syntax. ```csharp var greeting = $"Hello {name}"; ``` -------------------------------- ### Middleware Chaining (Gin/Echo/Fiber) Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/go.md Chain middleware functions using `Use()` or similar methods to apply them sequentially. Keep each middleware focused on a single responsibility. ```go router.Use(middleware1, middleware2) ``` -------------------------------- ### Architectural Health Report Structure Source: https://context7.com/bienhoang/refactoring-kit/llms.txt Example structure of the architectural health report, including detected style, module map, summary statistics, and pattern recommendations. ```markdown # Output report structure: ## Architectural Health Report: src/ ### Detected Style - Style: Hexagonal Architecture - Confidence: high - Dependency flow: Domain <- Application <- Infrastructure ### Module Map ```mermaid graph TD A[Domain] --> B[Application] B --> C[Infrastructure] C --> D[External APIs] ``` ### Summary - Modules scanned: 8 - Architectural smells: 4 (1 critical, 2 major, 1 minor) - Boundary violations: 2 - Circular dependencies: 1 ### Pattern Recommendations | Smell | Recommended Pattern | YAGNI Gate | Effort | |-------|-------------------|------------|--------| | Scattered Feature | Facade | passes | 2 days | | Circular Deps | Dependency Inversion | passes | 1 day | ### Recommended Next Steps 1. Fix boundary violations in infrastructure layer 2. Run /refactor:plan for Feature Scattering remediation ``` -------------------------------- ### Flask Extension Initialization Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/python.md Initialize extensions using the `ext.init_app(app)` pattern for lazy initialization, rather than `ext = Ext(app)` at import time. ```python Use `ext.init_app(app)` pattern (lazy initialization) not `ext = Ext(app)` at import time ``` -------------------------------- ### Serverless Style Detection Score Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/architecture/architectural-styles.md Example of how directory patterns contribute to scoring the Serverless architectural style. A score of +35 is awarded for matching 'functions/' and 'serverless.yml'. ```markdown | Directory Pattern | Layered | Hexagonal | Clean | EDA | Microservices | Modular | Pipe-Filter | Serverless | |-------------------|---------|-----------|-------|-----|---------------|---------|-------------|------------| | `functions/` + `serverless.yml` | | | | | | | | +35 | ``` -------------------------------- ### Refactoring Implementation Workflow Source: https://context7.com/bienhoang/refactoring-kit/llms.txt Outlines the step-by-step process the refactoring implementation tool follows, including loading plans, applying transformations, running tests, and handling failures. ```markdown # Plan execution workflow: # 1. Load plan.md, detect next incomplete phase # 2. Read phase file, extract transformation tasks # 3. Safeguard - run baseline tests # 4. For each transformation: # a. Apply single refactoring technique # b. Run tests (auto-detect: pytest, jest, go test, cargo test) # c. If fail -> revert with `git restore`, ask user # d. If pass -> suggest commit, proceed to next # 5. Code review changes after phase complete # 6. Update phase status to DONE # 7. Report summary with before/after metrics ``` -------------------------------- ### Uninstall Command - Commander CLI Source: https://github.com/bienhoang/refactoring-kit/blob/main/docs/code-standards.md Uninstalls refactoring kit skills from specified tools. Options are similar to the install command, including --global and --dry-run. ```bash refactoring-kit uninstall [--tool=] [--global] [--dry-run] ``` -------------------------------- ### Optimize Command Pipelines Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/shell-bash.md Reduce excessive subshell spawning by combining commands or using shell built-ins. For example, `awk` can often replace `cat | grep | awk`. ```shell cat file | grep pat | awk '{print $1}' ``` ```shell awk '/pat/ {print $1}' file ``` -------------------------------- ### Use Context Managers for Resource Management Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/python.md Replace repeated try/finally blocks for resource management with context managers created using `contextlib.contextmanager`. ```python Replace repeated try/finally → context manager (`contextlib.contextmanager`) ``` -------------------------------- ### ExMachina: Factory Usage Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/elixir.md Shows how to use ExMachina factories to build or insert test data. `build(:user)` creates a user struct, while `insert(:user)` persists it to the database. ```elixir build(:user) ``` ```elixir insert(:user) ``` -------------------------------- ### Use Flat Module Structure Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/lua.md Simplify code by adopting a flat module structure, where each file represents a single module returning a flat table. Avoid deeply nested namespaces. ```lua -- Instead of utils.math.string.helper -- Create a separate math_utils.lua file: local M = {} function M.add(a, b) return a + b end return M ``` -------------------------------- ### Replace Nested Conditional with Guard Clauses (Before) Source: https://context7.com/bienhoang/refactoring-kit/llms.txt Demonstrates a code structure with deep nesting and arrow-shaped logic, which is difficult to read and maintain. This is the 'before' state for the refactoring example. ```python # Before - Deep nesting, arrow-shaped code def pay(employee): if employee.is_active: if employee.is_full_time: if employee.has_benefits: return calculate_full_pay(employee) else: return calculate_partial_pay(employee) else: return calculate_part_time_pay(employee) else: return 0 ``` -------------------------------- ### Code Smell Categories and Examples Source: https://context7.com/bienhoang/refactoring-kit/llms.txt Illustrates common code smell categories like Bloaters, Change Preventers, Dispensables, and Couplers, along with their characteristics and suggested fixes. ```yaml # Code smell categories and examples: # Bloaters - Code grown too large - Long Method: >20 lines, multiple abstractions Severity: Major Fix: Extract Method, Decompose Conditional - God Class: >300 lines, >7 instance variables Severity: Major Fix: Extract Class, Extract Subclass - Long Parameter List: >3-4 parameters Severity: Major Fix: Introduce Parameter Object # Change Preventers - Makes changes difficult - Shotgun Surgery: One change touches 10+ files Severity: Critical Fix: Move Method/Field to consolidate # Dispensables - Unnecessary code - Duplicate Code: Same code in 2+ places Severity: Major Fix: Extract Method, Template Method pattern # Couplers - Excessive coupling - Feature Envy: Method uses another class more than its own Severity: Major Fix: Move Method # Priority scoring formula: Score = (Severity × Frequency × Impact) / Effort # Decision tiers: # - Quick Win: Score > 30, Effort < 1 day # - Strategic: Score 15-30, aligns with roadmap # - Planned: Score < 15, schedule for tech debt sprint ``` -------------------------------- ### Execute Refactoring from Plan File (Mode A) Source: https://context7.com/bienhoang/refactoring-kit/llms.txt Use this command to execute a refactoring plan by specifying the path to the `plan.md` file. The tool will process phases and transformations sequentially. ```bash # Mode A: Execute from plan file /refactor:implement plans/refactor-services/plan.md ``` -------------------------------- ### Use Scope Functions for Initialization and Transformation Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/kotlin.md Employ scope functions like `apply`, `also`, `let`, `run`, and `with` for cleaner initialization and transformation of objects. ```kotlin obj.apply { property = value } ``` ```kotlin obj.also { println(it) } ``` ```kotlin obj.let { process(it) } ``` ```kotlin obj.run { calculate() } ``` ```kotlin with(obj) { configure() } ``` -------------------------------- ### ASP.NET Core DI Registration Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/csharp.md Register services with the dependency injection container in ASP.NET Core, specifying their lifetime. This example shows registering a service with a scoped lifetime. ```csharp builder.Services.AddScoped(); ``` -------------------------------- ### Go: Os/Exec.Command with Unsanitized Input Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/security-smells.md Using os/exec.Command() with unsanitized input can lead to command injection vulnerabilities. Prefer passing arguments as a slice to Command. ```go os/exec.Command ``` -------------------------------- ### C# 12 Collection Expressions Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/csharp.md Utilize collection expressions for concise initialization of arrays and other collections. This example demonstrates the C# 12 syntax for creating an integer array. ```csharp int[] nums = [1, 2, 3]; ``` -------------------------------- ### Flask Blueprints for Organization Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/python.md Organize routes by domain using Blueprints and register them within the app factory. ```python Split routes into blueprints by domain; register in factory ``` -------------------------------- ### Python Characterization Test Example Source: https://github.com/bienhoang/refactoring-kit/blob/main/REFERENCE.md Use this pattern to write characterization tests that capture current behavior before refactoring. Ensure the observed output is asserted to lock in the behavior. ```python # Pattern: Characterization test def test_existing_behavior_description(): """Captures current behavior before refactoring.""" result = function_under_refactor(known_input) assert result == observed_current_output # Lock in behavior ``` -------------------------------- ### Testing: Use Quick/Nimble Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/swift.md Employ the Quick and Nimble frameworks for Behavior-Driven Development (BDD) style testing in Swift. Use `describe`, `context`, `it`, and `expect` for structuring tests. ```swift import Quick import Nimble class MySpec: QuickSpec { override func spec() { describe("a collection") { context("when empty") { it("is empty") { expect([]).to(beEmpty()) } } } } } ``` -------------------------------- ### Neovim API Usage Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/lua.md Utilize vim.api.nvim_* for buffer, window, and autocommand operations in Neovim. ```lua vim.api.nvim_* ``` -------------------------------- ### Find Unused/Missing Imports in Python Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/dependency-analysis.md Install and run deptry to detect unused or missing import statements in your Python project. This command should be executed in your project's root directory. ```bash pip install deptry && deptry . ``` -------------------------------- ### Flutter Widget Test Example Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/dart.md Perform widget testing in Flutter using 'flutter_test'. The 'tester' object provides methods to interact with widgets. Use 'testWidgets' for async operations. ```dart testWidgets('desc', (tester) async { ... }) ``` -------------------------------- ### Implement Full Type Hinting in PHP Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/php.md Ensure all function parameters and return types are declared. Use `mixed` if a parameter can truly accept any type, and `void` for functions that do not return a value. ```PHP // Smell: function process($data) // Fix: Add type declarations function process(array $data): ProcessResult { // ... implementation } ``` ```PHP // Smell: public function save($entity) // Fix: Add return type declaration public function save(Entity $entity): void { // ... implementation } ``` -------------------------------- ### Replace Nested Conditional with Guard Clauses (After) Source: https://context7.com/bienhoang/refactoring-kit/llms.txt Shows the refactored code using guard clauses and early returns for a flatter, more readable structure. This is the 'after' state of the refactoring example. ```python # After - Flat structure with early returns def pay(employee): if not employee.is_active: return 0 if not employee.is_full_time: return calculate_part_time_pay(employee) if not employee.has_benefits: return calculate_partial_pay(employee) return calculate_full_pay(employee) ``` -------------------------------- ### List Supported refactoring-kit Tools Source: https://github.com/bienhoang/refactoring-kit/blob/main/README.md View a list of all supported AI tools for the refactoring-kit. ```bash npx refactoring-kit tools ``` -------------------------------- ### Handle Exceptions with Logging Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/php.md Avoid empty catch blocks by logging the exception details before re-throwing or handling. ```php catch (\Throwable $e) { // Log error, re-throw, or handle // Example: $this->logger->error($e->getMessage(), ['exception' => $e]); // throw $e; } ``` -------------------------------- ### C# 12 Primary Constructors Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/csharp.md Simplify class and struct definitions by using primary constructors for direct initialization of fields. This example shows a service class with a primary constructor. ```csharp class UserService(IRepository repo) ``` -------------------------------- ### Testing: Use Swift Testing Macro Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/swift.md For Swift 5.9+ projects, consider using the Swift Testing framework with the `@Test` and `#expect` macros as a modern alternative to XCTest. ```swift import Testing @Test func testExample() { #expect(true) } ``` -------------------------------- ### Break Down Complex LINQ Queries Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/csharp.md Improve readability and debuggability of complex LINQ chains by breaking them into multiple steps with named intermediate variables. This example demonstrates splitting a query. ```csharp var activeUsers = users.Where(u => u.IsActive); var sorted = activeUsers.OrderBy(u => u.Name); ``` -------------------------------- ### Repository Pattern Structure Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/architecture/architectural-patterns.md Illustrates the directory structure for implementing the Repository Pattern, separating domain entities, repository interfaces, and data store implementations. ```typescript domain/ order.ts # Domain entity (no DB knowledge) ports/ order-repository.ts # Interface: findById, save, delete adapters/ postgres-order-repo.ts # Implementation: actual SQL/ORM in-memory-order-repo.ts # Test implementation ``` -------------------------------- ### Extract to Constants for Magic Numbers/Strings Source: https://github.com/bienhoang/refactoring-kit/blob/main/references/languages/csharp.md Replace literal values in business logic with named constants for better readability and maintainability. This example shows replacing a magic number with a constant. ```csharp if (retryCount > 3) → if (retryCount > MaxRetries) ```