suggest-simplification

Identify and suggest code simplification opportunities, including detection and recommendations for extractable methods, complex expressions, redundant code, and refactoring points.

Last repository push
GitHub Stars
109
Forks
26
Issues / PRs
1

Installation

Review the source and dependencies with a prompt. A package is available to download.

Install with an AI assistant

Copy the prompt so your assistant can review the pinned revision and dependencies first.

View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "suggest-simplification" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-11f0f4e0d70ebd0c824f9bcc7e025516674eefadedc234c51a83e3a862bf7a37. Verify the upstream source and version against https://github.com/dykyi-roman/awesome-claude-code before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.

Source and setup

github.com

Setup guidance pending

See the original source for supported tools, dependencies, and permissions.

Installation test pending

Identify and suggest code simplification opportunities, including detection and recommendations for extractable methods, complex expressions, redundant code, and refactoring points.

0 Downloads

Introduction source: third_party · dykyi-roman · 0.0.1 Reference

SkillPi interpretation

Tasks
Suggests code simplification opportunities. Identifies extract method candidates, complex expressions, redundant code, refactoring opportunities.
Inputs and outputs
```markdown
Testing
Not tested

Browse files

Browse files at the source ↗

Original SKILL.md

Open original ↗
Frontmatter
name: suggest-simplification
description: Suggests code simplification opportunities. Identifies extract method candidates, complex expressions, redundant code, refactoring opportunities.

Code Simplification Suggestions

Analyze PHP code for simplification and refactoring opportunities.

Simplification Patterns

1. Extract Method

// BEFORE: Long inline code block
public function processOrder(Order $order): void
{
    // Validate order (5 lines)
    if ($order->getItems()->isEmpty()) {
        throw new EmptyOrderException();
    }
    if ($order->getTotal()->isNegative()) {
        throw new InvalidTotalException();
    }

    // Process payment (10 lines)
    $payment = $this->paymentGateway->charge(
        $order->getTotal(),
        $order->getPaymentMethod()
    );
    if (!$payment->isSuccessful()) {
        throw new PaymentFailedException();
    }

    // Send notifications (5 lines)
    $this->mailer->send($order->getCustomer()->getEmail(), 'order_confirmed');
}

// AFTER: Extracted methods
public function processOrder(Order $order): void
{
    $this->validateOrder($order);
    $this->processPayment($order);
    $this->sendConfirmation($order);
}

private function validateOrder(Order $order): void {}
private function processPayment(Order $order): Payment {}
private function sendConfirmation(Order $order): void {}

2. Introduce Explaining Variable

// BEFORE: Complex expression
if ($user->getSubscription()?->isActive()
    && $user->getCreatedAt() < new DateTime('-30 days')
    && !$user->hasUsedTrial()
    && $user->getOrderCount() > 0) {
    $this->offerUpgrade($user);
}

// AFTER: Named variables
$hasActiveSubscription = $user->getSubscription()?->isActive();
$isEstablishedUser = $user->getCreatedAt() < new DateTime('-30 days');
$eligibleForUpgrade = !$user->hasUsedTrial() && $user->getOrderCount() > 0;

if ($hasActiveSubscription && $isEstablishedUser && $eligibleForUpgrade) {
    $this->offerUpgrade($user);
}

// EVEN BETTER: Extract to method
if ($user->isEligibleForUpgrade()) {
    $this->offerUpgrade($user);
}

3. Remove Redundant Code

// BEFORE: Redundant checks
if ($value !== null) {
    if ($value !== null) {  // Duplicate check
        $this->process($value);
    }
}

// BEFORE: Unnecessary else
if ($condition) {
    return $a;
} else {
    return $b;
}

// AFTER: Simplified
if ($condition) {
    return $a;
}
return $b;

// BEFORE: Redundant boolean
if ($condition === true) {}
return $value === true;

// AFTER: Simplified
if ($condition) {}
return $value;

4. Simplify Conditionals

// BEFORE: Nested conditionals
if ($user !== null) {
    if ($user->isActive()) {
        if ($user->hasPermission('edit')) {
            return true;
        }
    }
}
return false;

// AFTER: Combined condition
return $user !== null
    && $user->isActive()
    && $user->hasPermission('edit');

// BEFORE: Negative condition
if (!$items->isEmpty()) {
    $this->process($items);
}

// AFTER: Positive condition
if ($items->isNotEmpty()) {
    $this->process($items);
}

5. Replace Temp with Query

// BEFORE: Temporary variable used once
$basePrice = $order->getBasePrice();
$discount = $basePrice * 0.1;
return $basePrice - $discount;

// AFTER: Inline or method
return $order->getBasePrice() * 0.9;

// Or if complex:
return $order->getBasePrice() - $this->calculateDiscount($order);

6. Use Collection Methods

// BEFORE: Manual loop
$active = [];
foreach ($users as $user) {
    if ($user->isActive()) {
        $active[] = $user;
    }
}

// AFTER: array_filter
$active = array_filter($users, fn($user) => $user->isActive());

// BEFORE: Manual map
$emails = [];
foreach ($users as $user) {
    $emails[] = $user->getEmail();
}

// AFTER: array_map
$emails = array_map(fn($user) => $user->getEmail(), $users);

// BEFORE: Manual find
$found = null;
foreach ($items as $item) {
    if ($item->getId() === $id) {
        $found = $item;
        break;
    }
}

// AFTER: Collection method
$found = $collection->first(fn($item) => $item->getId() === $id);

7. Replace Switch with Polymorphism

// BEFORE: Switch on type
public function calculateShipping(Order $order): Money
{
    switch ($order->getShippingMethod()) {
        case 'standard':
            return $this->calculateStandardShipping($order);
        case 'express':
            return $this->calculateExpressShipping($order);
        case 'overnight':
            return $this->calculateOvernightShipping($order);
        default:
            throw new InvalidMethodException();
    }
}

// AFTER: Strategy pattern
interface ShippingCalculator {
    public function calculate(Order $order): Money;
}

class StandardShipping implements ShippingCalculator {}
class ExpressShipping implements ShippingCalculator {}

public function calculateShipping(Order $order): Money
{
    return $this->shippingCalculators
        ->get($order->getShippingMethod())
        ->calculate($order);
}

8. Null Object Pattern

// BEFORE: Null checks everywhere
if ($user->getAddress() !== null) {
    echo $user->getAddress()->getCity();
} else {
    echo 'Unknown';
}

// AFTER: Null Object
class NullAddress implements AddressInterface
{
    public function getCity(): string
    {
        return 'Unknown';
    }
}

// Always safe to call
echo $user->getAddress()->getCity();

9. Guard Clauses

// BEFORE: Deeply nested
public function process(Request $request): Response
{
    if ($request !== null) {
        if ($request->isValid()) {
            if ($this->canProcess($request)) {
                return $this->doProcess($request);
            } else {
                return $this->error('Cannot process');
            }
        } else {
            return $this->error('Invalid request');
        }
    } else {
        return $this->error('No request');
    }
}

// AFTER: Guard clauses
public function process(Request $request): Response
{
    if ($request === null) {
        return $this->error('No request');
    }

    if (!$request->isValid()) {
        return $this->error('Invalid request');
    }

    if (!$this->canProcess($request)) {
        return $this->error('Cannot process');
    }

    return $this->doProcess($request);
}

10. Use Modern PHP Features

// BEFORE: Old syntax
$name = isset($data['name']) ? $data['name'] : 'default';

// AFTER: Null coalescing
$name = $data['name'] ?? 'default';

// BEFORE: Property assignment
$value = $object->getValue();
if ($value !== null) {
    echo $value;
}

// AFTER: Nullsafe operator
echo $object?->getValue();

// BEFORE: Match as if/else
if ($status === 'active') {
    $color = 'green';
} elseif ($status === 'pending') {
    $color = 'yellow';
} else {
    $color = 'red';
}

// AFTER: Match expression
$color = match($status) {
    'active' => 'green',
    'pending' => 'yellow',
    default => 'red',
};

Severity Classification

Pattern Severity
Deeply nested code 🟠 Major
Repeated code blocks 🟠 Major
Complex boolean expressions 🟡 Minor
Old syntax available in modern PHP 🟢 Suggestion
Verbose but clear code 🟢 Suggestion

Output Format

### Simplification: [Description]

**Severity:** 🟠/🟡/🟢
**Location:** `file.php:line`
**Type:** [Extract Method|Guard Clause|Collection Method|...]

**Issue:**
[Description of the complexity]

**Current:**
```php
// Complex code

Suggested:

// Simplified code

Benefits:

  • Improved readability
  • Reduced cognitive load
  • Easier testing
  • Better reusability

Current listing version

0.0.1

Verify the source revision ↗

Quality assessment

Out of 100 · Assessment report from SkillPi LAB.

Scenario Value75/100

Highlights

  • 面向PHP开发者提供代码简化建议,具有明确的实用价值
  • 覆盖多种重构模式,适用于日常开发场景
Trigger Precision85/100

Highlights

  • 触发词完整覆盖多种变体,边界清晰
  • description准确描述了Skill的核心功能
Structure and Standards90/100

Highlights

  • Phase/步骤清晰,有端到端示例
  • frontmatter完整,文档结构良好
Execution Reliability80/100

Highlights

  • 工具来源明确,参数正确
  • 覆盖主要异常,不可逆操作有确认机制
Evidence Verifiability (mean of the first four)83/100

The arithmetic mean of the first four original scores, rounded to a whole number.

Static text checks

100 / 100 · skillpi-20261123-no-r3-v1

No current rules matched the text.

This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.

Permissions and checks before use

Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.

These common operations were not identified in the main document. This does not mean no permissions or risks exist.

These notices grant no permissions. Your host tool must still confirm file changes, secrets, external transfers or costs as needed.

Security rating and access scope

safe · Static evidence review; not a runtime safety guarantee.

Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.