File size: 16,824 Bytes
b6a9d74
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{"id": "db2a1c2d70a56cb9", "language": "python", "smell_type": "long_method", "severity": "high", "code_snippet": "def process_order(order_id, user_id, discount_code, shipping_address, payment_method):\n    conn = get_db()\n    order = conn.execute(\"SELECT * FROM orders WHERE id=?\", (order_id,)).fetchone()\n    if not order:\n        raise ValueError(\"Order not found\")\n    user = conn.execute(\"SELECT * FROM users WHERE id=?\", (user_id,)).fetchone()\n    if not user:\n        raise ValueError(\"User not found\")\n    if discount_code:\n        discount = conn.execute(\"SELECT * FROM discounts WHERE code=?\", (discount_code,)).fetchone()\n        if not discount:\n            raise ValueError(\"Invalid discount code\")\n        if discount['expiry'] < datetime.now():\n            raise ValueError(\"Discount expired\")\n        discount_amount = order['total'] * discount['percentage'] / 100\n    else:\n        discount_amount = 0\n    final_total = order['total'] - discount_amount\n    if payment_method == 'credit_card':\n        charge = stripe.charge_create(amount=final_total, currency='usd', customer=user['stripe_id'])\n        if charge['status'] != 'succeeded':\n            raise RuntimeError(\"Payment failed\")\n    elif payment_method == 'paypal':\n        result = paypal.create_payment(amount=final_total, payer_id=user['paypal_id'])\n        if result['state'] != 'approved':\n            raise RuntimeError(\"PayPal payment failed\")\n    conn.execute(\"UPDATE orders SET status='paid', total=? WHERE id=?\", (final_total, order_id))\n    send_email(user['email'], \"Order Confirmed\", f\"Your order {order_id} is confirmed.\")\n    send_sms(user['phone'], f\"Order {order_id} paid: ${final_total:.2f}\")\n    log_audit(user_id, 'order_paid', {'order_id': order_id, 'total': final_total})\n    conn.commit()\n    return {'order_id': order_id, 'total': final_total, 'status': 'paid'}", "smell_explanation": "The function handles order lookup, user validation, discount calculation, two payment methods, DB updates, email/SMS notifications, and audit logging all in one 40+ line method. It violates the Single Responsibility Principle and is extremely hard to test in isolation.", "refactoring_suggestion": "Extract discrete concerns into focused helpers: validate_order_and_user(), apply_discount(), charge_payment(method, amount, user), notify_user(user, order), and audit_log(). The orchestrator function then delegates to these, each independently testable.", "difficulty": "intermediate"}
{"id": "76ff8842726d8338", "language": "python", "smell_type": "dead_code", "severity": "medium", "code_snippet": "class UserService:\n    def get_user(self, user_id: int):\n        return self.repo.find(user_id)\n\n    def _legacy_get_user(self, user_id: int):\n        \"\"\"Deprecated. Use get_user() instead.\"\"\"\n        conn = sqlite3.connect('old.db')\n        return conn.execute('SELECT * FROM users WHERE id=?', (user_id,)).fetchone()\n\n    def _build_user_query_v1(self, filters):\n        # Used by old API endpoint \u2014 endpoint removed 2024-03\n        pass\n\n    def migrate_to_new_format(self, data):\n        # One-time migration script run 2024-01\n        pass", "smell_explanation": "Three methods (_legacy_get_user, _build_user_query_v1, migrate_to_new_format) are deprecated, removed, or one-time operations. They add cognitive overhead and may confuse contributors into calling or maintaining them.", "refactoring_suggestion": "Delete all three methods. Their history is preserved in git log. If migration scripts are valuable to keep, they belong in a separate migrations/ directory, not as instance methods of a live service class.", "difficulty": "beginner"}
{"id": "58f539bc7a63ec92", "language": "python", "smell_type": "middle_man", "severity": "medium", "code_snippet": "class EmailNotifier:\n    def __init__(self, smtp_client):\n        self._client = smtp_client\n\n    def send(self, to, subject, body):\n        return self._client.send(to, subject, body)\n\n    def send_html(self, to, subject, html):\n        return self._client.send_html(to, subject, html)\n\n    def bulk_send(self, recipients, subject, body):\n        return self._client.bulk_send(recipients, subject, body)", "smell_explanation": "EmailNotifier is a pure pass-through \u2014 every method delegates to smtp_client with identical signatures and zero added logic. It provides no value and makes callers learn an extra layer.", "refactoring_suggestion": "Inject smtp_client directly wherever EmailNotifier is used. If domain-specific logic is ever added (retries, template rendering, audit logging), introduce EmailNotifier at that point.", "difficulty": "beginner"}
{"id": "19c52cdd19229ef1", "language": "rust", "smell_type": "parallel_inheritance", "severity": "medium", "code_snippet": "// Every new format requires additions in TWO trait impls:\ntrait Encoder { fn encode(&self, data: &[u8]) -> Vec<u8>; }\ntrait Decoder { fn decode(&self, data: &[u8]) -> Vec<u8>; }\n\nstruct GzipEncoder; impl Encoder for GzipEncoder { fn encode(&self, d: &[u8]) -> Vec<u8> { ... } }\nstruct GzipDecoder; impl Decoder for GzipDecoder { fn decode(&self, d: &[u8]) -> Vec<u8> { ... } }\n\nstruct ZstdEncoder; impl Encoder for ZstdEncoder { fn encode(&self, d: &[u8]) -> Vec<u8> { ... } }\nstruct ZstdDecoder; impl Decoder for ZstdDecoder { fn decode(&self, d: &[u8]) -> Vec<u8> { ... } }", "smell_explanation": "Adding a new compression format (e.g., Brotli) requires two new structs across two parallel trait impls. The pairing is implicit \u2014 nothing enforces that GzipEncoder and GzipDecoder stay in sync.", "refactoring_suggestion": "Define a single trait: trait Codec { fn encode(&self, data: &[u8]) -> Vec<u8>; fn decode(&self, data: &[u8]) -> Vec<u8>; } Implemented by struct Gzip; and struct Zstd;. One struct per format, one trait hierarchy.", "difficulty": "intermediate"}
{"id": "09ebed95760c1eb9", "language": "typescript", "smell_type": "comments_as_smell", "severity": "low", "code_snippet": "// Array to store users\nconst users: User[] = [];\n\n// Loop through each user in the database results\nfor (const row of dbRows) {\n    // Create a new User object from the row\n    const user = new User(row.id, row.name, row.email);\n    // Push the user to the array\n    users.push(user);\n}\n\n// Return the array of users\nreturn users;", "smell_explanation": "Six comments explain code that is already self-documenting. The comment 'Array to store users' repeats the variable name; 'Loop through each user' restates the for loop. Comments like these rot as code evolves.", "refactoring_suggestion": "Delete all comments and use a cleaner mapping pattern: return dbRows.map(row => new User(row.id, row.name, row.email)). Well-named identifiers eliminate the need for explanatory prose.", "difficulty": "beginner"}
{"id": "f9665544b1bd121f", "language": "go", "smell_type": "feature_envy", "severity": "medium", "code_snippet": "func FormatUserCard(u *User) string {\n    var status string\n    if u.BannedAt != nil {\n        status = \"banned\"\n    } else if u.VerifiedAt == nil {\n        status = \"unverified\"\n    } else {\n        status = \"active\"\n    }\n    age := time.Now().Year() - u.BirthYear\n    return fmt.Sprintf(\"%s %s | %s | Age %d | %s\",\n        u.FirstName, u.LastName, u.Email, age, status)\n}", "smell_explanation": "FormatUserCard computes user status and age by accessing BannedAt, VerifiedAt, and BirthYear \u2014 derived facts that are User's own responsibility. The formatter knows more about User's business logic than User does.", "refactoring_suggestion": "Add (u *User) Status() string, (u *User) Age() int, and (u *User) FullName() string methods. FormatUserCard becomes: fmt.Sprintf(\"%s | %s | Age %d | %s\", u.FullName(), u.Email, u.Age(), u.Status()).", "difficulty": "beginner"}
{"id": "ef0c00500740ea81", "language": "go", "smell_type": "primitive_obsession", "severity": "medium", "code_snippet": "func CreateSession(userID string, token string, expiresAt int64, ipAddress string, userAgent string) error {\n    if len(token) < 32 {\n        return fmt.Errorf(\"token too short\")\n    }\n    if expiresAt < time.Now().Unix() {\n        return fmt.Errorf(\"already expired\")\n    }\n    // store session...\n    return nil\n}", "smell_explanation": "userID, token, expiresAt, ipAddress, and userAgent are all primitives. The function validates them individually, and any caller must know the ordering of five parameters \u2014 easy to mix up strings.", "refactoring_suggestion": "Introduce a Session struct: type Session struct { UserID UserID; Token Token; ExpiresAt time.Time; IP net.IP; UserAgent string }. Validation belongs in a NewSession constructor. CreateSession accepts *Session.", "difficulty": "beginner"}
{"id": "3829c5e49681d8bb", "language": "java", "smell_type": "incomplete_library", "severity": "medium", "code_snippet": "public class CollectionUtils {\n    public static <T> List<T> filter(List<T> list, Predicate<T> pred) {\n        List<T> result = new ArrayList<>();\n        for (T item : list) {\n            if (pred.test(item)) result.add(item);\n        }\n        return result;\n    }\n\n    public static <T, R> List<R> map(List<T> list, Function<T, R> fn) {\n        List<R> result = new ArrayList<>();\n        for (T item : list) result.add(fn.apply(item));\n        return result;\n    }\n}", "smell_explanation": "Home-rolled filter and map utilities duplicate Java Streams (list.stream().filter(pred).collect(toList())) which are available since Java 8. Maintaining bespoke collection utilities when the standard library already provides them is waste.", "refactoring_suggestion": "Delete CollectionUtils and use Java Streams: list.stream().filter(pred).collect(Collectors.toList()); list.stream().map(fn).collect(Collectors.toList()). Or use Collectors.toUnmodifiableList() in Java 10+.", "difficulty": "beginner"}
{"id": "6c1e5c7507beebd4", "language": "java", "smell_type": "inappropriate_intimacy", "severity": "high", "code_snippet": "public class ReportScheduler {\n    private final ReportService service;\n\n    public void scheduleMonthlyReport(LocalDate month) {\n        // Directly manipulates ReportService's internal state\n        service.pendingReports.add(new Report(month, \"monthly\"));\n        service.reportCounter++;\n        service.lastScheduledAt = LocalDateTime.now();\n        // Bypasses service.schedule() entirely\n    }\n}", "smell_explanation": "ReportScheduler directly writes to ReportService.pendingReports, reportCounter, and lastScheduledAt \u2014 bypassing the service's own schedule() method and its invariants (e.g., deduplication, counter bounds, notification triggers).", "refactoring_suggestion": "Call service.schedule(month, \"monthly\") and let ReportService manage its own internal state. If the scheduler needs feedback, service.schedule() returns a ScheduleResult. ReportScheduler should not know that pendingReports is a List.", "difficulty": "intermediate"}
{"id": "0bbabc8071b208fd", "language": "rust", "smell_type": "message_chains", "severity": "medium", "code_snippet": "fn get_admin_email(org: &Organization) -> Option<String> {\n    org.get_admin()\n       .and_then(|u| u.get_contact())\n       .and_then(|c| c.get_primary_email())\n       .map(|e| e.address().to_string())\n}", "smell_explanation": "Four chained Option combinators navigate Organization \u2192 User \u2192 Contact \u2192 Email. While idiomatic in Rust for Option handling, the chain still couples this function to four intermediate types and makes adding null-safety at any step require restructuring the chain.", "refactoring_suggestion": "Add Organization.admin_email() -> Option<String> that encapsulates the traversal. The method name communicates intent; the chain details are hidden. Callers call org.admin_email() instead of navigating the type hierarchy.", "difficulty": "intermediate"}
{"id": "16fd4e146b15d41e", "language": "go", "smell_type": "lazy_class", "severity": "low", "code_snippet": "type Validator struct{}\n\nfunc (v Validator) IsPositive(n int) bool {\n    return n > 0\n}", "smell_explanation": "A struct with no fields and one method that wraps a single comparison. There is no state to encapsulate and no polymorphism to provide \u2014 the method could be a package-level function.", "refactoring_suggestion": "Replace with: func IsPositive(n int) bool { return n > 0 }. Reserve structs with no fields for interface implementations where the zero-value receiver is meaningful, not for grouping trivially simple utility functions.", "difficulty": "beginner"}
{"id": "66db7b5168dfbe1a", "language": "go", "smell_type": "data_clumps", "severity": "low", "code_snippet": "func SearchProducts(minPrice, maxPrice float64, minRating, maxRating float64, minStock, maxStock int) []Product {\n    ...\n}\n\nfunc FilterProducts(minPrice, maxPrice float64, minRating, maxRating float64, category string) []Product {\n    ...\n}", "smell_explanation": "Price range, rating range, and stock range always appear as pairs of primitives in every product query function. The pairing is implicit and the ordering (min before max) must be remembered by callers.", "refactoring_suggestion": "Introduce PriceRange{Min, Max float64}, RatingRange{Min, Max float64}, StockRange{Min, Max int} types. Alternatively, a single ProductFilter struct consolidates all criteria, making zero-value (no filter) the natural default.", "difficulty": "beginner"}
{"id": "c46591dc4d305b7f", "language": "go", "smell_type": "none", "severity": "none", "code_snippet": "type Money struct {\n    amount   int64  // stored in cents\n    currency string // ISO 4217\n}\n\nfunc NewMoney(amount int64, currency string) (Money, error) {\n    if amount < 0 {\n        return Money{}, fmt.Errorf(\"amount must be non-negative\")\n    }\n    if len(currency) != 3 {\n        return Money{}, fmt.Errorf(\"invalid currency code\")\n    }\n    return Money{amount: amount, currency: currency}, nil\n}\n\nfunc (m Money) Add(other Money) (Money, error) {\n    if m.currency != other.currency {\n        return Money{}, fmt.Errorf(\"currency mismatch: %s vs %s\", m.currency, other.currency)\n    }\n    return Money{amount: m.amount + other.amount, currency: m.currency}, nil\n}", "smell_explanation": "Clean value object pattern: Money is immutable, validated at construction, stores currency-safe integer amounts, and arithmetic is type-safe. No smell \u2014 this is idiomatic Go domain modelling.", "refactoring_suggestion": "No refactoring needed. This is a textbook value object implementation.", "difficulty": "intermediate"}
{"id": "25131982e69188b3", "language": "typescript", "smell_type": "feature_envy", "severity": "medium", "code_snippet": "class SubscriptionRenewal {\n  renew(user: User): boolean {\n    const daysLeft = Math.floor(\n      (user.subscription.expiresAt.getTime() - Date.now()) / (1000 * 60 * 60 * 24)\n    );\n    const isEligible = daysLeft <= 30 && user.subscription.autoRenew && user.paymentMethod !== null;\n    if (isEligible) {\n      user.subscription.expiresAt = addMonths(user.subscription.expiresAt, user.subscription.plan.durationMonths);\n      user.subscription.renewalCount++;\n    }\n    return isEligible;\n  }\n}", "smell_explanation": "SubscriptionRenewal reaches into user.subscription.expiresAt, autoRenew, plan.durationMonths, and renewalCount. All of this logic belongs on Subscription: isEligibleForRenewal() and renew().", "refactoring_suggestion": "Add Subscription.daysRemaining(), Subscription.isEligibleForRenewal(), and Subscription.renew(). SubscriptionRenewal.renew(user) becomes: if (user.subscription.isEligibleForRenewal()) { user.subscription.renew(); return true; } return false;", "difficulty": "intermediate"}
{"id": "a8ff617a49b0be43", "language": "typescript", "smell_type": "dead_code", "severity": "medium", "code_snippet": "interface UserV1 { id: number; name: string; }            // Old API\ninterface UserV2 { id: string; fullName: string; }        // Current API\n\nfunction convertV1ToV2(user: UserV1): UserV2 {            // Run once at migration\n  return { id: String(user.id), fullName: user.name };\n}\n\nconst LEGACY_USER_CACHE: Map<number, UserV1> = new Map(); // Never populated", "smell_explanation": "UserV1, convertV1ToV2, and LEGACY_USER_CACHE are migration artifacts from a completed schema change. They are never referenced in current code, pollute the type namespace, and confuse developers about which User type to use.", "refactoring_suggestion": "Delete UserV1, convertV1ToV2, and LEGACY_USER_CACHE. The migration is complete \u2014 git history records how it was done. Keeping dead type aliases causes TypeScript to suggest them in autocomplete alongside the live types.", "difficulty": "beginner"}