code-smell-detection / code_smell_detection.jsonl
SalutefaceAAC's picture
Add full dataset JSONL (all splits combined)
accc0fe verified
Raw History Blame Contribute Delete
116 kB
{"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": "011f2d8c44970ff2", "language": "python", "smell_type": "god_object", "severity": "high", "code_snippet": "class Application:\n def __init__(self):\n self.users = []\n self.orders = []\n self.products = []\n self.db_conn = None\n self.email_client = None\n self.cache = {}\n self.logger = None\n self.config = {}\n\n def create_user(self, name, email): ...\n def delete_user(self, user_id): ...\n def authenticate_user(self, email, password): ...\n def create_order(self, user_id, items): ...\n def cancel_order(self, order_id): ...\n def apply_discount(self, order_id, code): ...\n def add_product(self, name, price, stock): ...\n def restock_product(self, product_id, qty): ...\n def send_email(self, to, subject, body): ...\n def send_sms(self, phone, msg): ...\n def generate_invoice(self, order_id): ...\n def export_csv(self, entity_type): ...\n def backup_database(self): ...\n def clear_cache(self): ...\n def rotate_logs(self): ...", "smell_explanation": "The Application class owns every domain concept (users, orders, products), every infrastructure concern (DB, email, cache, logging), and every operation in the system. It will grow without bound and create merge conflicts for every developer.", "refactoring_suggestion": "Decompose into bounded-context classes: UserService, OrderService, ProductService, NotificationService, and infrastructure adapters (DatabaseAdapter, CacheAdapter). Wire them via dependency injection rather than a single monolith.", "difficulty": "intermediate"}
{"id": "34ebdf3cd3996658", "language": "python", "smell_type": "feature_envy", "severity": "medium", "code_snippet": "class Report:\n def __init__(self, data_source):\n self.data_source = data_source\n\n def generate(self):\n records = self.data_source.records\n total = sum(r.amount for r in self.data_source.records if r.status == 'paid')\n overdue = [r for r in self.data_source.records if r.due_date < datetime.today() and r.status != 'paid']\n avg = total / len(self.data_source.records) if self.data_source.records else 0\n return {'total_paid': total, 'overdue_count': len(overdue), 'average': avg}", "smell_explanation": "Report.generate() repeatedly reaches into data_source internals (records, amounts, statuses, due_dates). The method is more interested in DataSource's data than in Report's own responsibilities \u2014 a classic Feature Envy.", "refactoring_suggestion": "Move the aggregation logic to DataSource as paid_total(), overdue_records(), and average_amount() methods. Report.generate() then just calls data_source.summary().", "difficulty": "beginner"}
{"id": "ec61164a1f725772", "language": "python", "smell_type": "primitive_obsession", "severity": "medium", "code_snippet": "def schedule_meeting(user_id, start_hour, start_minute, duration_minutes, room_name, building, floor):\n if start_hour < 0 or start_hour > 23:\n raise ValueError(\"Invalid hour\")\n if start_minute < 0 or start_minute > 59:\n raise ValueError(\"Invalid minute\")\n if duration_minutes < 15:\n raise ValueError(\"Meeting too short\")\n end_minute = (start_minute + duration_minutes) % 60\n end_hour = start_hour + (start_minute + duration_minutes) // 60\n room_code = f\"{building}-{floor}-{room_name}\"\n ...", "smell_explanation": "Time is represented as two separate integers (hour, minute), location as three separate strings. Validation and arithmetic are scattered across callers. Primitive types carry no domain semantics.", "refactoring_suggestion": "Introduce TimeSlot(start: datetime, duration: timedelta) and Room(building, floor, name) value objects. Validation lives inside the constructors; callers pass meaningful objects rather than raw primitives.", "difficulty": "beginner"}
{"id": "9365cd0d376e2ed8", "language": "python", "smell_type": "data_clumps", "severity": "medium", "code_snippet": "def send_payment(card_number, card_expiry, card_cvv, card_holder, amount, currency):\n validate_card(card_number, card_expiry, card_cvv)\n charge = gateway.charge(card_number, card_expiry, card_cvv, card_holder, amount, currency)\n return charge\n\ndef refund_payment(card_number, card_expiry, card_cvv, card_holder, charge_id, amount):\n validate_card(card_number, card_expiry, card_cvv)\n return gateway.refund(card_number, card_expiry, card_cvv, charge_id, amount)", "smell_explanation": "The four card fields (number, expiry, cvv, holder) always travel together across every function signature. Data clumps like this indicate a missing abstraction and increase the risk of parameter ordering mistakes.", "refactoring_suggestion": "Create a CreditCard dataclass with number, expiry, cvv, holder fields. Pass a single CreditCard object; validation becomes card.validate(). Callers gain readability and type safety.", "difficulty": "beginner"}
{"id": "0fb4db6386940a81", "language": "python", "smell_type": "speculative_generality", "severity": "low", "code_snippet": "class EventPublisher:\n def __init__(self, strategy=None, serializer=None, retry_policy=None, middleware=None):\n self.strategy = strategy or DefaultStrategy()\n self.serializer = serializer or JsonSerializer()\n self.retry_policy = retry_policy or NoRetry()\n self.middleware = middleware or []\n\n def publish(self, event, channel=None, priority=None, ttl=None, trace_id=None):\n # Only JSON + default channel are ever used in practice\n return self.strategy.dispatch(self.serializer.serialize(event), channel or 'default')", "smell_explanation": "The class has four pluggable strategies and publish() has five parameters, but the codebase only ever calls EventPublisher().publish(event). The generality is speculative \u2014 no current caller needs any of these extension points.", "refactoring_suggestion": "Remove unused parameters and strategy injection. If new use cases emerge, add them at that point (YAGNI). Simple version: EventPublisher(channel).publish(event) backed by a single JSON serializer.", "difficulty": "beginner"}
{"id": "5a87b4c9ef2f403d", "language": "python", "smell_type": "comments_as_smell", "severity": "low", "code_snippet": "def calc(x, y, z):\n # multiply x by y\n r1 = x * y\n # add z to the result of multiplying x by y\n r2 = r1 + z\n # return the final result\n return r2", "smell_explanation": "Every line is explained by a comment that restates what the code literally does. This is a sign the code is insufficiently expressive \u2014 comments are compensating for poor naming rather than explaining non-obvious intent.", "refactoring_suggestion": "Rename to make intent obvious: def weighted_sum(value, weight, offset): return value * weight + offset. Delete all comments; the code now reads as its own documentation.", "difficulty": "beginner"}
{"id": "448d3d9f3fd3e56a", "language": "python", "smell_type": "temporary_field", "severity": "medium", "code_snippet": "class InvoiceGenerator:\n def __init__(self, order):\n self.order = order\n self.tax_rate = None # only set during generate()\n self.line_items = None # only set during generate()\n self.subtotal = None # only set during generate()\n\n def generate(self):\n self.tax_rate = get_tax_rate(self.order.country)\n self.line_items = [LineItem(p, p.price) for p in self.order.products]\n self.subtotal = sum(li.total for li in self.line_items)\n tax = self.subtotal * self.tax_rate\n return Invoice(self.line_items, self.subtotal, tax)", "smell_explanation": "tax_rate, line_items, and subtotal are instance fields that are None except during generate(). They exist only to avoid passing locals between helper methods \u2014 a sign the class should not own them.", "refactoring_suggestion": "Make generate() a pure function that holds these as local variables, or extract an InvoiceContext dataclass returned by a compute_context(order) helper. Instance state should reflect the lifetime of the object, not one method call.", "difficulty": "intermediate"}
{"id": "99cf7685ddb2d324", "language": "python", "smell_type": "large_class", "severity": "high", "code_snippet": "class UserManager:\n # 400+ line class\n def register(self): ...\n def login(self): ...\n def logout(self): ...\n def reset_password(self): ...\n def change_email(self): ...\n def update_profile(self): ...\n def upload_avatar(self): ...\n def get_notifications(self): ...\n def mark_notification_read(self): ...\n def follow_user(self): ...\n def unfollow_user(self): ...\n def block_user(self): ...\n def get_feed(self): ...\n def get_recommendations(self): ...\n def export_data(self): ...\n def delete_account(self): ...", "smell_explanation": "UserManager is a 400-line class with 16 methods spanning authentication, profile management, avatar storage, notifications, social graph, feed, recommendations, and account deletion. It has many reasons to change simultaneously.", "refactoring_suggestion": "Split by cohesion: AuthService (register/login/logout/reset_password), ProfileService (update_profile/upload_avatar/export_data/delete_account), NotificationService, SocialService (follow/unfollow/block). Each has one clear purpose.", "difficulty": "intermediate"}
{"id": "44ff65890e33fb45", "language": "python", "smell_type": "message_chains", "severity": "medium", "code_snippet": "def get_city(user):\n return user.get_profile().get_address().get_location().get_city()\n\n# called as:\ncity = order.get_customer().get_profile().get_address().get_location().get_city()", "smell_explanation": "The message chain navigates five objects deep (customer \u2192 profile \u2192 address \u2192 location \u2192 city). Any intermediate object returning None causes an AttributeError; refactoring any intermediate class ripples everywhere.", "refactoring_suggestion": "Apply the Law of Demeter: add a user.city property that encapsulates the traversal, or use a Data Transfer Object that flattens the relevant fields. Callers should ask for data, not navigate object graphs.", "difficulty": "intermediate"}
{"id": "060fecc4469ed2a9", "language": "javascript", "smell_type": "long_method", "severity": "high", "code_snippet": "async function handleCheckout(req, res) {\n try {\n const { userId, cartId, couponCode, shippingAddress, paymentToken } = req.body;\n const user = await User.findById(userId);\n if (!user) return res.status(404).json({ error: 'User not found' });\n const cart = await Cart.findById(cartId).populate('items.product');\n if (!cart || cart.userId.toString() !== userId) return res.status(403).json({ error: 'Forbidden' });\n let discount = 0;\n if (couponCode) {\n const coupon = await Coupon.findOne({ code: couponCode, active: true });\n if (!coupon) return res.status(400).json({ error: 'Invalid coupon' });\n if (coupon.expiresAt < new Date()) return res.status(400).json({ error: 'Coupon expired' });\n discount = cart.total * coupon.discountPct / 100;\n }\n const finalTotal = cart.total - discount;\n const paymentResult = await stripe.charges.create({ amount: Math.round(finalTotal * 100), currency: 'usd', source: paymentToken });\n if (paymentResult.status !== 'succeeded') return res.status(402).json({ error: 'Payment failed' });\n const order = await Order.create({ userId, items: cart.items, total: finalTotal, status: 'confirmed' });\n await Cart.findByIdAndDelete(cartId);\n await sendOrderConfirmationEmail(user.email, order);\n await sendSlackNotification(`New order ${order._id} for $${finalTotal}`);\n res.status(201).json({ orderId: order._id, total: finalTotal });\n } catch (err) {\n console.error(err);\n res.status(500).json({ error: 'Internal server error' });\n }\n}", "smell_explanation": "A single Express handler performs user lookup, cart validation, coupon resolution, payment, order creation, cart cleanup, email, and Slack notification. It is impossible to unit-test any step in isolation and mixes HTTP concerns with business logic.", "refactoring_suggestion": "Extract validateUser, validateCart, applyCoupon, chargePayment, createOrder, and notifyChannels as separate async functions or service methods. The handler becomes a thin orchestrator. Business logic moves to services and can be tested without HTTP.", "difficulty": "intermediate"}
{"id": "02f7aaf1b083f735", "language": "javascript", "smell_type": "switch_statements", "severity": "medium", "code_snippet": "function getDiscount(userType, total) {\n let discount = 0;\n switch (userType) {\n case 'gold': discount = total * 0.20; break;\n case 'silver': discount = total * 0.10; break;\n case 'bronze': discount = total * 0.05; break;\n case 'vip': discount = total * 0.30; break;\n default: discount = 0;\n }\n return discount;\n}", "smell_explanation": "A switch on userType means every new tier requires modifying this function. The switch is duplicated wherever discount logic appears (invoicing, cart, reporting), making additions risky and forgetful.", "refactoring_suggestion": "Use a data-driven lookup: const DISCOUNT_RATES = { gold: 0.20, silver: 0.10, bronze: 0.05, vip: 0.30 }; return total * (DISCOUNT_RATES[userType] ?? 0). Or apply the Strategy/Policy pattern if tier logic grows more complex.", "difficulty": "beginner"}
{"id": "c21794d31a85dde6", "language": "javascript", "smell_type": "feature_envy", "severity": "medium", "code_snippet": "class OrderSummary {\n constructor(order) { this.order = order; }\n\n format() {\n const items = this.order.lineItems.map(li =>\n `${li.product.name} x${li.quantity} @ $${li.product.price.toFixed(2)}`\n );\n const tax = this.order.subtotal * this.order.taxRate;\n const total = this.order.subtotal + tax - this.order.discountAmount;\n return `Items:\\n${items.join('\\n')}\\nTax: $${tax.toFixed(2)}\\nTotal: $${total.toFixed(2)}`;\n }\n}", "smell_explanation": "format() knows intimate details of Order's lineItems, product names, prices, taxRate, subtotal, and discountAmount. The method belongs logically on Order itself, not on a wrapper class.", "refactoring_suggestion": "Add order.toSummaryString() (or order.formatReceipt()) and call it from OrderSummary.format(). Alternatively, pass a pre-computed OrderDTO with only the fields needed for display.", "difficulty": "beginner"}
{"id": "30c8fcfd41b6972a", "language": "javascript", "smell_type": "primitive_obsession", "severity": "high", "code_snippet": "function createEvent(title, startYear, startMonth, startDay, startHour, startMinute,\n endYear, endMonth, endDay, endHour, endMinute, locationLat, locationLng) {\n const start = new Date(startYear, startMonth - 1, startDay, startHour, startMinute);\n const end = new Date(endYear, endMonth - 1, endDay, endHour, endMinute);\n if (end <= start) throw new Error('End must be after start');\n return { title, start, end, location: { lat: locationLat, lng: locationLng } };\n}", "smell_explanation": "Thirteen primitive parameters for what is conceptually two datetimes and one coordinate pair. The long signature is error-prone (month-day-hour ordering), untestable in isolation, and impossible to read at call sites.", "refactoring_suggestion": "Accept { start: Date, end: Date, location: { lat, lng } }. Callers construct Date objects themselves, which is standard JS. Destructured options objects are self-documenting and extensible.", "difficulty": "beginner"}
{"id": "5947d2cfac3e2cb3", "language": "javascript", "smell_type": "god_object", "severity": "high", "code_snippet": "class App {\n constructor() {\n this.router = express();\n this.db = null;\n this.cache = null;\n this.mailer = null;\n this.jobs = [];\n this.sockets = [];\n this.metrics = {};\n }\n connectDB() { ... }\n connectRedis() { ... }\n registerRoutes() { ... }\n registerMiddleware() { ... }\n startWorkers() { ... }\n scheduleJobs() { ... }\n initWebSockets() { ... }\n sendEmail() { ... }\n trackMetric() { ... }\n shutdown() { ... }\n restart() { ... }\n}", "smell_explanation": "App owns the database, cache, mailer, job queue, WebSocket connections, metrics, routing, and lifecycle. It is a God Object: any change anywhere requires modifying this class, and tests require spinning up the entire system.", "refactoring_suggestion": "Follow composition root pattern: create DatabaseModule, CacheModule, MailModule, WorkerModule, etc. App's constructor wires them together but delegates all logic. Each module is independently configurable and testable.", "difficulty": "intermediate"}
{"id": "0d9ce3be63cb0499", "language": "javascript", "smell_type": "none", "severity": "none", "code_snippet": "class ShoppingCart {\n constructor() {\n this.items = [];\n }\n\n addItem(product, quantity) {\n const existing = this.items.find(i => i.product.id === product.id);\n if (existing) {\n existing.quantity += quantity;\n } else {\n this.items.push({ product, quantity });\n }\n }\n\n get total() {\n return this.items.reduce((sum, i) => sum + i.product.price * i.quantity, 0);\n }\n\n removeItem(productId) {\n this.items = this.items.filter(i => i.product.id !== productId);\n }\n}", "smell_explanation": "This class is clean: it has one clear responsibility (managing cart state), small well-named methods, no deep chains, no hidden state, and a natural getter for total. Each method does exactly one thing.", "refactoring_suggestion": "No refactoring needed. The class is a good example of a focused, cohesive value object.", "difficulty": "beginner"}
{"id": "fab47ff85e64731a", "language": "javascript", "smell_type": "inappropriate_intimacy", "severity": "medium", "code_snippet": "class OrderProcessor {\n constructor(order, inventory) {\n this.order = order;\n this.inventory = inventory;\n }\n\n process() {\n // Directly manipulates Inventory internals\n for (const item of this.order.items) {\n this.inventory._stockLevels[item.sku] -= item.qty;\n if (this.inventory._stockLevels[item.sku] < this.inventory._reorderThreshold[item.sku]) {\n this.inventory._pendingReorders.push(item.sku);\n }\n }\n }\n}", "smell_explanation": "OrderProcessor accesses three private fields (_stockLevels, _reorderThreshold, _pendingReorders) of Inventory. It knows Inventory's internal data structure, creating tight coupling that breaks whenever Inventory is refactored.", "refactoring_suggestion": "Inventory should expose: deduct(sku, qty) which handles stock decrement and triggers reorder internally. OrderProcessor calls inventory.deduct(item.sku, item.qty) and knows nothing about internals.", "difficulty": "intermediate"}
{"id": "c9abcfe40ffe3b49", "language": "javascript", "smell_type": "middle_man", "severity": "low", "code_snippet": "class UserService {\n constructor(userRepository) {\n this.repo = userRepository;\n }\n findById(id) { return this.repo.findById(id); }\n findByEmail(email) { return this.repo.findByEmail(email); }\n save(user) { return this.repo.save(user); }\n delete(id) { return this.repo.delete(id); }\n findAll() { return this.repo.findAll(); }\n}", "smell_explanation": "UserService adds no logic \u2014 every method is a one-liner delegation to userRepository. It is a pure Middle Man providing zero value while adding an extra layer to navigate and maintain.", "refactoring_suggestion": "Delete UserService and inject UserRepository directly. If domain logic is ever needed (e.g., password hashing, permission checks), add a real service at that point. Don't create layers speculatively.", "difficulty": "beginner"}
{"id": "6f46d668792b8cf5", "language": "typescript", "smell_type": "primitive_obsession", "severity": "medium", "code_snippet": "function createUser(\n name: string,\n email: string,\n streetAddress: string,\n city: string,\n state: string,\n zipCode: string,\n countryCode: string,\n phoneAreaCode: string,\n phoneNumber: string\n): User {\n // email validation inline\n if (!email.includes('@')) throw new Error('Invalid email');\n // zip validation inline\n if (!/^\\d{5}$/.test(zipCode)) throw new Error('Invalid zip');\n ...\n}", "smell_explanation": "Nine primitive parameters with inline validation scattered through the function. Address is clearly a domain concept (street + city + state + zip + country), as is PhoneNumber. Validation belongs in the types, not the callers.", "refactoring_suggestion": "Introduce Email, Address, and PhoneNumber value types with validation in their constructors. createUser(name: string, email: Email, address: Address, phone: PhoneNumber) is self-documenting and validation-safe.", "difficulty": "intermediate"}
{"id": "7ddfa806f5a3de61", "language": "typescript", "smell_type": "large_class", "severity": "high", "code_snippet": "class DashboardComponent {\n // 600 lines\n users: User[] = [];\n orders: Order[] = [];\n products: Product[] = [];\n selectedTab: string = 'users';\n searchQuery: string = '';\n sortColumn: string = '';\n sortDirection: 'asc' | 'desc' = 'asc';\n currentPage: number = 1;\n pageSize: number = 25;\n isLoading: boolean = false;\n errorMessage: string = '';\n // ... 12 more fields\n\n loadUsers() { ... }\n filterUsers() { ... }\n sortUsers() { ... }\n paginateUsers() { ... }\n loadOrders() { ... }\n filterOrders() { ... }\n exportUsersCSV() { ... }\n exportOrdersCSV() { ... }\n deleteUser(id: string) { ... }\n deleteOrder(id: string) { ... }\n // ... 20 more methods\n}", "smell_explanation": "A 600-line Angular/React component managing users, orders, and products with their own filtering, sorting, pagination, export, and deletion. UI components should display data, not own three separate domain entity lifecycles.", "refactoring_suggestion": "Decompose into UserTableComponent, OrderTableComponent, ProductTableComponent each with their own state and service injection. A slim DashboardComponent only handles tab selection and layout. Extract useUserTable, useOrderTable hooks (React) or sub-stores (Angular).", "difficulty": "advanced"}
{"id": "0429e21b0e6ce70f", "language": "typescript", "smell_type": "speculative_generality", "severity": "medium", "code_snippet": "interface Repository<T, ID = string, Q = Record<string, unknown>> {\n findById(id: ID): Promise<T | null>;\n findAll(query?: Q): Promise<T[]>;\n save(entity: T): Promise<T>;\n delete(id: ID): Promise<void>;\n count(query?: Q): Promise<number>;\n exists(id: ID): Promise<boolean>;\n bulkSave(entities: T[]): Promise<T[]>;\n bulkDelete(ids: ID[]): Promise<void>;\n paginate(query?: Q, page?: number, size?: number): Promise<{ data: T[]; total: number }>;\n stream(query?: Q): AsyncIterable<T>;\n}", "smell_explanation": "The Repository interface exposes 10 methods including bulkSave, stream, and paginate that zero concrete implementations use. Implementing this interface requires writing stub methods for every consumer, making it a speculative over-abstraction.", "refactoring_suggestion": "Start with the three methods actually needed: findById, save, delete. Add operations only when a use case requires them. Prefer small, cohesive interfaces (Interface Segregation Principle) over large ones.", "difficulty": "intermediate"}
{"id": "84e4707a4032bd4a", "language": "typescript", "smell_type": "none", "severity": "none", "code_snippet": "type Result<T, E = Error> =\n | { ok: true; value: T }\n | { ok: false; error: E };\n\nfunction divide(a: number, b: number): Result<number, string> {\n if (b === 0) return { ok: false, error: 'Division by zero' };\n return { ok: true, value: a / b };\n}\n\nconst result = divide(10, 2);\nif (result.ok) {\n console.log(result.value); // 5\n}", "smell_explanation": "Clean discriminated union for error handling \u2014 no exceptions for expected failures, exhaustive type narrowing, and the happy path is explicit. The function has a single responsibility and no smell.", "refactoring_suggestion": "No refactoring needed. This is a well-typed functional pattern for recoverable errors.", "difficulty": "intermediate"}
{"id": "6c64d425c27fe5a3", "language": "typescript", "smell_type": "refused_bequest", "severity": "high", "code_snippet": "abstract class Animal {\n name: string;\n abstract makeSound(): string;\n abstract fly(): string;\n abstract swim(): string;\n}\n\nclass Dog extends Animal {\n makeSound() { return 'Woof'; }\n fly() { throw new Error('Dogs cannot fly'); }\n swim() { return 'paddling'; }\n}\n\nclass Eagle extends Animal {\n makeSound() { return 'Screech'; }\n fly() { return 'soaring'; }\n swim() { throw new Error('Eagles do not swim'); }\n}", "smell_explanation": "Dog and Eagle are forced to implement methods they cannot meaningfully perform (fly for Dog, swim for Eagle), throwing runtime errors. Refused Bequest: subclasses reject inherited interfaces \u2014 a Liskov Substitution violation.", "refactoring_suggestion": "Segregate interfaces: interface Swimmer { swim(): string }, interface Flyer { fly(): string }. Animal only declares makeSound(). Dog implements Animal & Swimmer; Eagle implements Animal & Flyer. No class throws for unimplemented behavior.", "difficulty": "intermediate"}
{"id": "2d9f5e51d7dc2fe3", "language": "typescript", "smell_type": "data_clumps", "severity": "medium", "code_snippet": "function sendInvoice(\n recipientName: string,\n recipientEmail: string,\n recipientPhone: string,\n amount: number,\n currency: string,\n dueDate: Date\n): void { ... }\n\nfunction remindInvoice(\n recipientName: string,\n recipientEmail: string,\n recipientPhone: string,\n invoiceId: string\n): void { ... }", "smell_explanation": "recipientName, recipientEmail, recipientPhone form a data clump that appears together in every function signature related to communications. Adding a contact field (e.g., preferredLanguage) requires touching every signature.", "refactoring_suggestion": "Define interface Contact { name: string; email: string; phone: string; } and pass Contact objects. Functions become sendInvoice(recipient: Contact, amount: number, currency: string, dueDate: Date).", "difficulty": "beginner"}
{"id": "3219335a2cf7455f", "language": "go", "smell_type": "long_method", "severity": "high", "code_snippet": "func (h *Handler) ProcessWebhook(w http.ResponseWriter, r *http.Request) {\n body, err := io.ReadAll(r.Body)\n if err != nil {\n http.Error(w, \"read error\", http.StatusBadRequest)\n return\n }\n sig := r.Header.Get(\"X-Signature\")\n expected := computeHMAC(body, h.secret)\n if sig != expected {\n http.Error(w, \"invalid signature\", http.StatusUnauthorized)\n return\n }\n var event WebhookEvent\n if err := json.Unmarshal(body, &event); err != nil {\n http.Error(w, \"parse error\", http.StatusBadRequest)\n return\n }\n switch event.Type {\n case \"payment.succeeded\":\n order, err := h.db.GetOrder(event.OrderID)\n if err != nil { http.Error(w, \"db error\", 500); return }\n order.Status = \"paid\"\n if err := h.db.SaveOrder(order); err != nil { http.Error(w, \"save error\", 500); return }\n if err := h.mailer.Send(order.UserEmail, \"Payment received\", \"...\"); err != nil {\n h.log.Error(\"email failed\", err)\n }\n case \"payment.failed\":\n order, err := h.db.GetOrder(event.OrderID)\n if err != nil { http.Error(w, \"db error\", 500); return }\n order.Status = \"failed\"\n if err := h.db.SaveOrder(order); err != nil { http.Error(w, \"save error\", 500); return }\n case \"refund.issued\":\n // ... another 20 lines\n }\n w.WriteHeader(http.StatusOK)\n}", "smell_explanation": "A single HTTP handler validates signatures, parses JSON, and implements business logic for three event types inline. Adding a new webhook event type requires modifying this function, which touches HTTP plumbing at the same time.", "refactoring_suggestion": "Extract verifySignature(body, sig, secret) error, parseEvent(body) (*WebhookEvent, error), and a per-event handler: handlePaymentSucceeded, handlePaymentFailed, handleRefundIssued. The HTTP handler only orchestrates; a dispatch map replaces the switch.", "difficulty": "intermediate"}
{"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": "5f08474767da64df", "language": "go", "smell_type": "feature_envy", "severity": "medium", "code_snippet": "type Formatter struct{}\n\nfunc (f *Formatter) FormatUser(u *User) string {\n age := time.Now().Year() - u.BirthYear\n initials := string(u.FirstName[0]) + string(u.LastName[0])\n status := \"active\"\n if u.DeletedAt != nil {\n status = \"deleted\"\n }\n return fmt.Sprintf(\"%s %s (%s, age %d) [%s]\", u.FirstName, u.LastName, initials, age, status)\n}", "smell_explanation": "Formatter.FormatUser reaches into User's BirthYear, DeletedAt, and name fields to compute age, initials, and status \u2014 knowledge that belongs on User. Formatter is more interested in User than in its own formatting concerns.", "refactoring_suggestion": "Add User.Age() int, User.Initials() string, and User.StatusLabel() string methods. Formatter calls them: fmt.Sprintf(\"%s (%s, age %d) [%s]\", u.FullName(), u.Initials(), u.Age(), u.StatusLabel()).", "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": "3099f0bf11afc067", "language": "go", "smell_type": "large_class", "severity": "high", "code_snippet": "type UserService struct {\n db *sql.DB\n cache *redis.Client\n mailer *Mailer\n sms *SMSClient\n s3 *s3.Client\n stripe *stripe.Client\n}\n\n// 50+ methods including:\nfunc (s *UserService) Register(...) {}\nfunc (s *UserService) Login(...) {}\nfunc (s *UserService) ForgotPassword(...) {}\nfunc (s *UserService) UpdateProfile(...) {}\nfunc (s *UserService) UploadAvatar(...) {}\nfunc (s *UserService) GetFeed(...) {}\nfunc (s *UserService) Follow(...) {}\nfunc (s *UserService) Unsubscribe(...) {}\nfunc (s *UserService) ExportGDPR(...) {}\nfunc (s *UserService) DeleteAccount(...) {}\nfunc (s *UserService) ChargeSubscription(...) {}\nfunc (s *UserService) GenerateInvoice(...) {}", "smell_explanation": "UserService has six infrastructure dependencies and 50+ methods covering auth, profiles, media, social, billing, and compliance. It will require changes for every unrelated feature and be a merge-conflict magnet.", "refactoring_suggestion": "Decompose into AuthService, ProfileService, MediaService, SocialService, BillingService, ComplianceService. Each takes only its relevant dependencies. Wire them in the service layer via composition or interfaces.", "difficulty": "intermediate"}
{"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": "15f4a78447a06e4f", "language": "java", "smell_type": "long_method", "severity": "high", "code_snippet": "public ResponseEntity<OrderResponse> placeOrder(PlaceOrderRequest request) {\n User user = userRepo.findById(request.getUserId()).orElseThrow(() -> new NotFoundException(\"User not found\"));\n Cart cart = cartRepo.findByUserId(request.getUserId()).orElseThrow(() -> new NotFoundException(\"Cart empty\"));\n if (cart.getItems().isEmpty()) throw new BadRequestException(\"Cart is empty\");\n double subtotal = cart.getItems().stream().mapToDouble(i -> i.getProduct().getPrice() * i.getQuantity()).sum();\n double tax = subtotal * taxService.getRateForRegion(user.getRegion());\n double discount = 0;\n if (request.getCouponCode() != null) {\n Coupon coupon = couponRepo.findByCode(request.getCouponCode()).orElseThrow(() -> new BadRequestException(\"Invalid coupon\"));\n if (coupon.isExpired()) throw new BadRequestException(\"Coupon expired\");\n discount = subtotal * coupon.getDiscountPct() / 100.0;\n }\n double total = subtotal + tax - discount;\n Payment payment = paymentService.charge(request.getPaymentToken(), total, \"USD\");\n if (!payment.isSuccessful()) throw new PaymentException(\"Payment failed: \" + payment.getError());\n Order order = new Order(user, cart.getItems(), subtotal, tax, discount, total, payment.getId());\n orderRepo.save(order);\n cartRepo.delete(cart);\n emailService.sendOrderConfirmation(user.getEmail(), order);\n return ResponseEntity.ok(OrderResponse.from(order));\n}", "smell_explanation": "A 25-line method handles user lookup, cart validation, tax calculation, coupon resolution, payment charging, order persistence, cart cleanup, and email notification. Each step is a separate responsibility with its own failure modes.", "refactoring_suggestion": "Extract: validateAndGetCart(), calculatePricing(cart, user, coupon), chargePayment(token, amount), and persistOrder(user, cart, pricing, paymentId). The controller delegates to an OrderService, which delegates to focused collaborators.", "difficulty": "intermediate"}
{"id": "f64c3e6d07ca1183", "language": "java", "smell_type": "switch_statements", "severity": "high", "code_snippet": "public double calculateShipping(String carrierCode, double weight, String destination) {\n switch (carrierCode) {\n case \"FEDEX\":\n if (destination.equals(\"INTERNATIONAL\")) return weight * 8.5 + 15.0;\n return weight * 3.2 + 5.0;\n case \"UPS\":\n if (destination.equals(\"INTERNATIONAL\")) return weight * 9.0 + 12.0;\n return weight * 2.9 + 4.5;\n case \"USPS\":\n return weight * 1.8 + 3.0;\n case \"DHL\":\n return weight * 10.5 + 20.0;\n default:\n throw new IllegalArgumentException(\"Unknown carrier: \" + carrierCode);\n }\n}", "smell_explanation": "A switch on carrier codes with nested conditionals for destination. Adding a new carrier or changing a rate formula requires modifying this method, violating Open/Closed Principle. The logic will also be duplicated in related methods.", "refactoring_suggestion": "Use a strategy pattern: interface ShippingCarrier { double calculateRate(double weight, String destination); } with FedExCarrier, UpsCarrier, etc. A CarrierRegistry maps codes to implementations. calculateShipping delegates to the registry.", "difficulty": "intermediate"}
{"id": "48e1aafccfa79fdd", "language": "java", "smell_type": "lazy_class", "severity": "low", "code_snippet": "public class StringUtils {\n public static String capitalize(String s) {\n if (s == null || s.isEmpty()) return s;\n return Character.toUpperCase(s.charAt(0)) + s.toLowerCase().substring(1);\n }\n}", "smell_explanation": "StringUtils contains a single method that duplicates functionality already provided by Apache Commons Lang StringUtils.capitalize() or Spring's StringUtils. A one-method utility class rarely justifies its existence.", "refactoring_suggestion": "Delete StringUtils and use the standard library equivalent (org.apache.commons.lang3.StringUtils.capitalize), or inline the one-liner at the single call site if the dependency is not warranted.", "difficulty": "beginner"}
{"id": "3c51fbe48a2724fa", "language": "java", "smell_type": "alternative_classes", "severity": "medium", "code_snippet": "// Two classes doing the same thing with different names\nclass CustomerEmailSender {\n public void send(String to, String subject, String body) { ... }\n public void sendWithAttachment(String to, String subject, String body, File attachment) { ... }\n}\n\nclass UserNotificationMailer {\n public void sendEmail(String recipient, String title, String content) { ... }\n public void sendEmailWithFile(String recipient, String title, String content, File file) { ... }\n}", "smell_explanation": "Two classes with identical responsibilities and nearly identical method signatures but different names. Code that could share one email abstraction is split across two, causing inconsistent behavior and doubled maintenance.", "refactoring_suggestion": "Unify into a single EmailService (or Mailer) interface with send(EmailMessage) and merge both implementations. Choose one and migrate all callers. Identical abstractions with different names indicate a missed merge earlier.", "difficulty": "beginner"}
{"id": "d80130dea47f6a28", "language": "java", "smell_type": "none", "severity": "none", "code_snippet": "public final class Email {\n private final String value;\n\n private Email(String value) { this.value = value; }\n\n public static Email of(String value) {\n if (value == null || !value.contains(\"@\")) {\n throw new IllegalArgumentException(\"Invalid email: \" + value);\n }\n return new Email(value.trim().toLowerCase());\n }\n\n public String getValue() { return value; }\n\n @Override public String toString() { return value; }\n @Override public boolean equals(Object o) { ... }\n @Override public int hashCode() { ... }\n}", "smell_explanation": "Textbook immutable value object: validation at construction, no public constructor (factory method enforces invariants), equals/hashCode based on value. Correct, defensive, and idiomatic Java.", "refactoring_suggestion": "No refactoring needed. This is a well-implemented value object following DDD patterns.", "difficulty": "intermediate"}
{"id": "eb2a00655e929699", "language": "java", "smell_type": "large_class", "severity": "high", "code_snippet": "@Service\npublic class ProductService {\n // 800 lines, 40+ methods\n public Product createProduct(...) {}\n public Product updateProduct(...) {}\n public void deleteProduct(...) {}\n public List<Product> search(...) {}\n public void updateInventory(...) {}\n public void reserveStock(...) {}\n public void releaseStock(...) {}\n public void triggerReorder(...) {}\n public BigDecimal calculatePrice(...) {}\n public BigDecimal applyBulkDiscount(...) {}\n public void attachImage(...) {}\n public void removeImage(...) {}\n public ProductReview addReview(...) {}\n public void flagReview(...) {}\n public List<Product> getRecommendations(...) {}\n public void exportCatalog(...) {}\n}", "smell_explanation": "An 800-line service class covering CRUD, inventory management, pricing, media, reviews, recommendations, and exports. Each of these is a separate bounded context; a single Spring service violates SRP and makes bounded-context testing impossible.", "refactoring_suggestion": "Split: ProductCatalogService (CRUD + search), InventoryService (stock management + reorder), PricingService (price + discounts), MediaService (images), ReviewService (reviews + flagging), RecommendationService. Each injects only its relevant repositories.", "difficulty": "advanced"}
{"id": "a781a1e5f68e44c8", "language": "rust", "smell_type": "primitive_obsession", "severity": "medium", "code_snippet": "fn send_message(\n sender_id: u64,\n receiver_id: u64,\n content: String,\n timestamp: i64,\n channel: String,\n) -> Result<(), String> {\n if content.is_empty() {\n return Err(\"empty content\".into());\n }\n if timestamp < 0 {\n return Err(\"invalid timestamp\".into());\n }\n // ...\n Ok(())\n}", "smell_explanation": "Five primitive parameters: two u64 IDs that could be confused, a raw i64 timestamp (could be seconds or milliseconds), and a channel string with no validation. Callers pass bare integers with no semantic context.", "refactoring_suggestion": "Introduce newtype wrappers: UserId(u64), Timestamp(i64) (validate positive at construction), and Channel(String) (validate at construction). send_message signature becomes (sender: UserId, receiver: UserId, content: &str, at: Timestamp, channel: &Channel).", "difficulty": "intermediate"}
{"id": "98841ab5011051a7", "language": "rust", "smell_type": "long_method", "severity": "high", "code_snippet": "pub fn parse_config(path: &str) -> Result<Config, ConfigError> {\n let contents = std::fs::read_to_string(path)\n .map_err(|e| ConfigError::Io(e))?;\n let raw: serde_json::Value = serde_json::from_str(&contents)\n .map_err(|e| ConfigError::Parse(e))?;\n let host = raw[\"database\"][\"host\"].as_str()\n .ok_or(ConfigError::Missing(\"database.host\".into()))?;\n let port = raw[\"database\"][\"port\"].as_u64()\n .ok_or(ConfigError::Missing(\"database.port\".into()))? as u16;\n let db_name = raw[\"database\"][\"name\"].as_str()\n .ok_or(ConfigError::Missing(\"database.name\".into()))?;\n let redis_url = raw[\"cache\"][\"redis_url\"].as_str()\n .ok_or(ConfigError::Missing(\"cache.redis_url\".into()))?;\n let log_level = raw[\"logging\"][\"level\"].as_str().unwrap_or(\"info\");\n let max_connections = raw[\"pool\"][\"max_connections\"].as_u64().unwrap_or(10) as usize;\n // 30 more fields parsed the same way...\n Ok(Config { host: host.into(), port, db_name: db_name.into(), redis_url: redis_url.into(), log_level: log_level.into(), max_connections })\n}", "smell_explanation": "parse_config extracts every field inline, growing linearly as config schema grows. The function will reach 100+ lines; adding a new config section requires modifying it directly.", "refactoring_suggestion": "Derive serde::Deserialize on Config and its sub-structs (DatabaseConfig, CacheConfig, LoggingConfig, PoolConfig). parse_config becomes: serde_json::from_str(&contents).map_err(ConfigError::Parse). Zero boilerplate for each new field.", "difficulty": "intermediate"}
{"id": "3e8e04fb555373fb", "language": "rust", "smell_type": "feature_envy", "severity": "medium", "code_snippet": "struct ReportGenerator;\n\nimpl ReportGenerator {\n fn generate_summary(user: &User) -> String {\n let days_active = (Utc::now() - user.created_at).num_days();\n let tier = if user.subscription_points > 1000 { \"gold\" }\n else if user.subscription_points > 500 { \"silver\" }\n else { \"bronze\" };\n format!(\"{} ({}d active, {} tier, {} pts)\",\n user.name, days_active, tier, user.subscription_points)\n }\n}", "smell_explanation": "generate_summary accesses user.created_at, user.subscription_points, and user.name to compute derived facts (days_active, tier) that logically belong on User itself.", "refactoring_suggestion": "Add impl User { fn days_active(&self) -> i64, fn tier(&self) -> &str, fn summary(&self) -> String }. ReportGenerator calls user.summary() or composes the parts via user's own methods.", "difficulty": "beginner"}
{"id": "0a1ee9ced63f2fc3", "language": "rust", "smell_type": "none", "severity": "none", "code_snippet": "#[derive(Debug, Clone, PartialEq)]\npub struct Temperature {\n celsius: f64,\n}\n\nimpl Temperature {\n pub fn from_celsius(c: f64) -> Result<Self, &'static str> {\n if c < -273.15 {\n return Err(\"below absolute zero\");\n }\n Ok(Temperature { celsius: c })\n }\n\n pub fn from_fahrenheit(f: f64) -> Result<Self, &'static str> {\n Self::from_celsius((f - 32.0) * 5.0 / 9.0)\n }\n\n pub fn celsius(&self) -> f64 { self.celsius }\n pub fn fahrenheit(&self) -> f64 { self.celsius * 9.0 / 5.0 + 32.0 }\n}", "smell_explanation": "Clean newtype value object: private field, validated constructors, unit-converting accessors, derived traits. Represents a domain concept (temperature) with its own invariants. No smell.", "refactoring_suggestion": "No refactoring needed. This is idiomatic Rust domain modelling with proper encapsulation.", "difficulty": "intermediate"}
{"id": "002fcf160adc5571", "language": "rust", "smell_type": "large_class", "severity": "medium", "code_snippet": "pub struct Server {\n config: Config,\n db_pool: PgPool,\n cache: RedisPool,\n router: Router,\n mailer: Mailer,\n job_queue: Queue,\n metrics: MetricsRegistry,\n auth: AuthService,\n}\n\nimpl Server {\n pub fn new(...) -> Self { ... }\n pub async fn start(&self) { ... }\n pub async fn stop(&self) { ... }\n pub async fn reload_config(&self) { ... }\n pub async fn health_check(&self) -> HealthStatus { ... }\n pub async fn drain_connections(&self) { ... }\n pub fn register_route(&mut self, ...) { ... }\n pub async fn emit_metric(&self, ...) { ... }\n pub async fn send_email(&self, ...) { ... }\n pub async fn enqueue_job(&self, ...) { ... }\n}", "smell_explanation": "Server owns eight infrastructure services and has methods spanning routing, health, lifecycle, configuration, metrics, email, and job queuing. Infrastructure cross-cutting concerns are directly owned instead of delegated.", "refactoring_suggestion": "Server should own AppState and call axum/actix's server runtime. Email, metrics, and job queuing should be injected as Arc<dyn Trait> interfaces. Server's impl covers only start/stop/health \u2014 other concerns live in their own types.", "difficulty": "advanced"}
{"id": "7c2357c947e69522", "language": "rust", "smell_type": "speculative_generality", "severity": "medium", "code_snippet": "pub trait Processor<I, O, E, C = ()> {\n type Config: Default;\n fn process(&self, input: I, config: Option<C>) -> Result<O, E>;\n fn process_batch(&self, inputs: Vec<I>, config: Option<C>) -> Vec<Result<O, E>>;\n fn validate(&self, input: &I) -> bool;\n fn transform(&self, output: O) -> O;\n fn on_error(&self, error: &E);\n}", "smell_explanation": "A five-method generic trait with four type parameters where the entire codebase contains a single impl \u2014 EmailProcessor \u2014 that uses only process() and ignores process_batch, transform, and on_error with no-op defaults. Over-abstracted for one use case.", "refactoring_suggestion": "Start with: trait Processor<I, O> { fn process(&self, input: I) -> Result<O, ProcessError>; }. Add batch/transform/config only when a second implementor actually needs them. Generic abstractions should be discovered, not designed upfront.", "difficulty": "advanced"}
{"id": "09c2850421b8dffc", "language": "python", "smell_type": "inappropriate_intimacy", "severity": "high", "code_snippet": "class OrderExporter:\n def __init__(self, order_service):\n self.service = order_service\n\n def export_to_csv(self, user_id):\n # Directly accesses internal cache dict\n orders = self.service._order_cache.get(user_id, [])\n # Bypasses query method, accesses raw DB cursor\n extra = list(self.service._db._cursor.execute(\n \"SELECT * FROM orders WHERE user_id=? AND status='archived'\", (user_id,)\n ))\n return [*orders, *extra]", "smell_explanation": "OrderExporter accesses _order_cache (a private dict) and _db._cursor (a private cursor) of OrderService, coupling itself to two levels of internal implementation detail. Any internal refactoring of OrderService silently breaks the exporter.", "refactoring_suggestion": "OrderService should expose get_all_orders(user_id, include_archived=True) -> List[Order]. OrderExporter calls that public method. No knowledge of caches or cursors leaks out.", "difficulty": "intermediate"}
{"id": "3e75505def4ccddb", "language": "python", "smell_type": "dead_code", "severity": "low", "code_snippet": "class Config:\n DEBUG = True\n DATABASE_URL = 'postgresql://localhost/prod'\n SECRET_KEY = 'change-me'\n\n # Legacy config from old Redis integration \u2014 no longer used\n REDIS_HOST = 'localhost'\n REDIS_PORT = 6379\n REDIS_PASSWORD = ''\n REDIS_DB = 0\n\n @staticmethod\n def from_old_format(data):\n \"\"\"Deprecated: use Config.from_env() instead\"\"\"\n pass", "smell_explanation": "Four Redis config fields and a deprecated from_old_format() method are never referenced anywhere in the codebase. Dead code increases cognitive overhead and may confuse contributors into thinking Redis is a live dependency.", "refactoring_suggestion": "Remove the REDIS_* fields and from_old_format(). If Redis is reintroduced later, add it then with proper documentation. Git history preserves the old code if needed.", "difficulty": "beginner"}
{"id": "e5f297007150600a", "language": "python", "smell_type": "parallel_inheritance", "severity": "medium", "code_snippet": "# Every time you add a new shape, you must add a class in TWO hierarchies:\nclass Shape: pass\nclass Circle(Shape): pass\nclass Rectangle(Shape): pass\n\nclass ShapeRenderer: pass\nclass CircleRenderer(ShapeRenderer): pass\nclass RectangleRenderer(ShapeRenderer): pass\n\nclass ShapeSerializer: pass\nclass CircleSerializer(ShapeSerializer): pass\nclass RectangleSerializer(ShapeSerializer): pass", "smell_explanation": "Adding a Triangle requires creating three classes: Triangle, TriangleRenderer, TriangleSerializer. The parallel hierarchies move in lockstep \u2014 a classic Parallel Inheritance smell that makes extension laborious and error-prone.", "refactoring_suggestion": "Use the Visitor or Double Dispatch pattern: ShapeRenderer.render(shape) dispatches on shape type using a dict or isinstance checks. Alternatively, give each Shape its own render() and serialize() methods (absorbing the behavior), collapsing the hierarchies into one.", "difficulty": "advanced"}
{"id": "2b4b3985eb7d888a", "language": "python", "smell_type": "none", "severity": "none", "code_snippet": "from dataclasses import dataclass\nfrom typing import List\n\n@dataclass(frozen=True)\nclass Address:\n street: str\n city: str\n country: str\n postal_code: str\n\n def __post_init__(self):\n if not self.postal_code:\n raise ValueError(\"postal_code required\")\n if len(self.country) != 2:\n raise ValueError(\"country must be ISO 3166-1 alpha-2\")\n\n@dataclass\nclass Order:\n id: str\n items: List[str]\n shipping_address: Address\n\n @property\n def item_count(self) -> int:\n return len(self.items)", "smell_explanation": "Clean value objects: Address is frozen (immutable) with self-validating __post_init__, Order is a mutable aggregate with a derived property. No smell \u2014 proper data modelling with Python dataclasses.", "refactoring_suggestion": "No refactoring needed. This is idiomatic Python domain modelling.", "difficulty": "beginner"}
{"id": "b222a3a933d0de54", "language": "python", "smell_type": "incomplete_library", "severity": "low", "code_snippet": "import csv\n\ndef write_csv(rows, filepath, encoding='utf-8'):\n with open(filepath, 'w', newline='', encoding=encoding) as f:\n writer = csv.DictWriter(f, fieldnames=rows[0].keys())\n writer.writeheader()\n writer.writerows(rows)\n\ndef read_csv(filepath, encoding='utf-8'):\n with open(filepath, encoding=encoding) as f:\n return list(csv.DictReader(f))", "smell_explanation": "This wraps Python's built-in csv module with thin wrappers that add no meaningful value \u2014 the standard csv.DictWriter/DictReader API is already this simple. Wrapping it creates a non-standard interface callers must learn.", "refactoring_suggestion": "Delete the wrappers and use csv.DictWriter/DictReader directly at call sites. If helpers are genuinely needed (e.g., atomic writes, gzip support), the added feature should justify the wrapper.", "difficulty": "beginner"}
{"id": "106472d7ff00d631", "language": "javascript", "smell_type": "parallel_inheritance", "severity": "medium", "code_snippet": "// Every new payment provider requires additions in THREE places:\nclass PaymentProcessor { process() {} }\nclass StripeProcessor extends PaymentProcessor { process() {} }\nclass PaypalProcessor extends PaymentProcessor { process() {} }\n\nclass PaymentLogger { log() {} }\nclass StripeLogger extends PaymentLogger { log() {} }\nclass PaypalLogger extends PaymentLogger { log() {} }\n\nclass PaymentValidator { validate() {} }\nclass StripeValidator extends PaymentValidator { validate() {} }\nclass PaypalValidator extends PaymentValidator { validate() {} }", "smell_explanation": "Adding a new payment provider (e.g., Square) requires three new subclasses across three parallel hierarchies. The parallel structure grows lockstep, indicating coupling between class trees that should be collapsed.", "refactoring_suggestion": "Merge into a single PaymentProvider interface: { process(), log(), validate() }. StripeProvider implements all three; PaypalProvider implements all three. One class per provider, one hierarchy.", "difficulty": "intermediate"}
{"id": "26126cacab6e5fa6", "language": "typescript", "smell_type": "god_object", "severity": "high", "code_snippet": "class AuthManager {\n private users: Map<string, User> = new Map();\n private sessions: Map<string, Session> = new Map();\n private tokens: Map<string, string> = new Map();\n private failedAttempts: Map<string, number> = new Map();\n private blockedIPs: Set<string> = new Set();\n private auditLog: AuditEntry[] = [];\n private emailQueue: EmailTask[] = [];\n\n register(email: string, password: string): User { ... }\n login(email: string, password: string, ip: string): Session { ... }\n logout(sessionId: string): void { ... }\n refreshToken(token: string): string { ... }\n resetPassword(email: string): void { ... }\n validateMFA(userId: string, code: string): boolean { ... }\n blockIP(ip: string): void { ... }\n getAuditLog(userId: string): AuditEntry[] { ... }\n sendVerificationEmail(userId: string): void { ... }\n purgeExpiredSessions(): void { ... }\n}", "smell_explanation": "AuthManager owns session storage, token management, IP blocking, audit logging, and email queuing in memory. It is both a domain service and an in-memory infrastructure layer, making it impossible to scale or replace any piece.", "refactoring_suggestion": "Split by concern: UserRepository (persistence), SessionService (session lifecycle), TokenService (JWT/refresh), RateLimiter (IP blocking), AuditService (audit log), and wire via interfaces. AuthService orchestrates, not stores.", "difficulty": "advanced"}
{"id": "321e9355abd0286c", "language": "javascript", "smell_type": "dead_code", "severity": "low", "code_snippet": "function calculateTax(amount, region) {\n // Old flat-rate logic kept for reference\n // const TAX_RATE = 0.08;\n // return amount * TAX_RATE;\n\n const rates = { US: 0.07, EU: 0.20, UK: 0.20 };\n return amount * (rates[region] ?? 0.10);\n}", "smell_explanation": "Two commented-out lines of old logic are preserved 'for reference.' Commented code in version control is noise \u2014 it clutters diffs, confuses readers, and is never actually referenced because nobody knows when it was valid.", "refactoring_suggestion": "Delete the commented lines. Git history preserves the old implementation if it is ever needed. If the flat rate had special significance, a code comment explaining WHY it was replaced is more valuable than the dead code itself.", "difficulty": "beginner"}
{"id": "81da26f8bf150d05", "language": "java", "smell_type": "refused_bequest", "severity": "high", "code_snippet": "abstract class Vehicle {\n abstract void accelerate();\n abstract void brake();\n abstract void refuel();\n abstract void fly();\n}\n\nclass Car extends Vehicle {\n void accelerate() { ... }\n void brake() { ... }\n void refuel() { ... }\n void fly() { throw new UnsupportedOperationException(\"Cars cannot fly\"); }\n}\n\nclass Airplane extends Vehicle {\n void accelerate() { ... }\n void brake() { ... }\n void refuel() { ... }\n void fly() { ... }\n}", "smell_explanation": "Car extends Vehicle but throws UnsupportedOperationException for fly() \u2014 a Refused Bequest and Liskov Substitution Principle violation. Any code that calls vehicle.fly() will fail at runtime for Car instances.", "refactoring_suggestion": "Segregate interfaces: interface GroundVehicle { void accelerate(); void brake(); void refuel(); } interface Aircraft extends GroundVehicle { void fly(); } Car implements GroundVehicle; Airplane implements Aircraft.", "difficulty": "intermediate"}
{"id": "319ef348aea8ff1f", "language": "java", "smell_type": "temporary_field", "severity": "medium", "code_snippet": "public class ReportBuilder {\n private List<String> headers; // only set in buildHeaders()\n private List<Row> rows; // only set in buildRows()\n private double grandTotal; // only set in buildRows()\n private String currency; // only set in buildRows()\n\n public Report build(DataSet data) {\n buildHeaders(data);\n buildRows(data);\n return new Report(headers, rows, grandTotal, currency);\n }\n}", "smell_explanation": "Four instance fields exist solely to share state between private methods within a single build() call. Outside of that call they are all null/zero, making the object's state unpredictable if any method is called out of order.", "refactoring_suggestion": "Extract a ReportContext record/class that holds headers, rows, grandTotal, currency and is passed between helpers: buildHeaders(data) -> List<String>, buildRows(data, headers) -> RowsResult. build() composes them as local variables.", "difficulty": "intermediate"}
{"id": "ce8a82840a168acb", "language": "java", "smell_type": "comments_as_smell", "severity": "medium", "code_snippet": "// Check if user is not null and has admin role\nif (user != null && user.getRole().equals(\"admin\")) {\n // Call the method to delete the resource\n resourceService.delete(resourceId);\n // Log that we deleted it\n logger.info(\"Resource \" + resourceId + \" was deleted\");\n}", "smell_explanation": "Every line has a comment restating what the code already says. The comment before the if-block describes the condition in plain English \u2014 information that clear variable names and method calls already convey.", "refactoring_suggestion": "Remove all comments. Rename to make intent visible: if (user != null && user.isAdmin()) { resourceService.delete(resourceId); log.info(\"Deleted resource {}\", resourceId); }. The code now reads as its own documentation.", "difficulty": "beginner"}
{"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": "c41bc10e8a7f937a", "language": "go", "smell_type": "comments_as_smell", "severity": "low", "code_snippet": "// GetUserByID returns the user with the given ID\nfunc GetUserByID(id int) (*User, error) {\n // Query the database for the user\n row := db.QueryRow(\"SELECT id, name, email FROM users WHERE id = ?\", id)\n // Create a new user struct\n user := &User{}\n // Scan the row into the user struct\n err := row.Scan(&user.ID, &user.Name, &user.Email)\n // Return the user or the error\n return user, err\n}", "smell_explanation": "The function doc comment is redundant with the function name; inline comments restate each line's obvious action. In Go, doc comments should describe behaviour, edge cases, or guarantees \u2014 not narrate the implementation.", "refactoring_suggestion": "Keep only a doc comment if it adds non-obvious context: // GetUserByID returns ErrNoRows if no user exists. Remove all inline comments. Code structure is already clear.", "difficulty": "beginner"}
{"id": "0bd8a1a71089e3ea", "language": "rust", "smell_type": "comments_as_smell", "severity": "low", "code_snippet": "// Function to calculate factorial\nfn factorial(n: u64) -> u64 {\n // If n is 0 return 1\n if n == 0 {\n return 1; // base case\n }\n // Otherwise multiply n by factorial of n-1\n n * factorial(n - 1)\n}", "smell_explanation": "Four comments explain a well-known recursive algorithm that any programmer recognises. The comments add zero information and will become misleading if the implementation changes (e.g., to iterative).", "refactoring_suggestion": "Remove all comments. The function name factorial and parameter n are sufficient. If non-obvious invariants exist (e.g., panics on n > 20 due to overflow), document those \u2014 not the recursion itself.", "difficulty": "beginner"}
{"id": "482efafe5f2edfac", "language": "python", "smell_type": "comments_as_smell", "severity": "medium", "code_snippet": "class Calculator:\n # Initialize the calculator\n def __init__(self):\n # Set history to empty list\n self.history = []\n\n # Add two numbers\n def add(self, a, b):\n # Calculate the sum\n result = a + b\n # Append result to history\n self.history.append(result)\n # Return the result\n return result", "smell_explanation": "Every statement is narrated by a comment that restates it verbatim. The class docstring and method docstrings would be appropriate places for intent \u2014 but only if there were non-obvious constraints to document (precision, overflow, etc.).", "refactoring_suggestion": "Delete all inline comments. If the class has non-obvious constraints (e.g., history is capped at 1000 entries), document only that. Otherwise the code is already clear: def add(self, a, b): result = a + b; self.history.append(result); return result.", "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": "4587ead1f94ede37", "language": "go", "smell_type": "middle_man", "severity": "medium", "code_snippet": "type CacheService struct {\n client *redis.Client\n}\n\nfunc (c *CacheService) Get(key string) (string, error) { return c.client.Get(ctx, key).Result() }\nfunc (c *CacheService) Set(key, value string, ttl time.Duration) error { return c.client.Set(ctx, key, value, ttl).Err() }\nfunc (c *CacheService) Delete(key string) error { return c.client.Del(ctx, key).Err() }\nfunc (c *CacheService) Exists(key string) (bool, error) {\n n, err := c.client.Exists(ctx, key).Result()\n return n > 0, err\n}", "smell_explanation": "CacheService wraps Redis with identical signatures for Get, Set, Delete, and a trivially thin Exists. The only transformation is a bool conversion that could be a one-liner at the call site. The layer adds indirection without benefit.", "refactoring_suggestion": "Inject *redis.Client directly (or the redis.Cmdable interface for testability). If you need a cache abstraction for testing, define a minimal interface: type Cache interface { Get(key string) (string, error); Set(key, value string, ttl time.Duration) error } and implement it with a thin adapter, not a forwarding class.", "difficulty": "intermediate"}
{"id": "fdc902f976171a01", "language": "java", "smell_type": "middle_man", "severity": "low", "code_snippet": "public class LoggerWrapper {\n private final Logger log = LoggerFactory.getLogger(LoggerWrapper.class);\n\n public void info(String msg) { log.info(msg); }\n public void warn(String msg) { log.warn(msg); }\n public void error(String msg) { log.error(msg); }\n public void debug(String msg) { log.debug(msg); }\n}", "smell_explanation": "LoggerWrapper adds nothing over the SLF4J Logger it wraps \u2014 same method signatures, no enrichment. Every class that uses it must depend on a non-standard type instead of the ubiquitous Logger.", "refactoring_suggestion": "Delete LoggerWrapper and use SLF4J Logger directly: private static final Logger log = LoggerFactory.getLogger(MyClass.class). If custom enrichment is needed (e.g., MDC, correlation IDs), extend using a proper filter or interceptor, not a wrapper class.", "difficulty": "beginner"}
{"id": "771a25b0509eabf4", "language": "typescript", "smell_type": "middle_man", "severity": "medium", "code_snippet": "class ProductRepository {\n constructor(private db: Database) {}\n\n findById(id: string): Promise<Product | null> { return this.db.findById<Product>('products', id); }\n findAll(): Promise<Product[]> { return this.db.findAll<Product>('products'); }\n save(product: Product): Promise<Product> { return this.db.save('products', product); }\n delete(id: string): Promise<void> { return this.db.delete('products', id); }\n}", "smell_explanation": "ProductRepository merely forwards every call to a generic Database with the 'products' table name hardcoded. There is no product-specific query logic \u2014 it is a Middle Man that hides the generic DB API behind a named fa\u00e7ade.", "refactoring_suggestion": "If the only value is the hardcoded table name, use a partial application or a factory: db.collectionFor<Product>('products'). Introduce a real ProductRepository only when you need product-specific queries (e.g., findBySlug, findByCategory).", "difficulty": "intermediate"}
{"id": "2cfca8a54b860739", "language": "python", "smell_type": "lazy_class", "severity": "low", "code_snippet": "class DateHelper:\n @staticmethod\n def today():\n from datetime import date\n return date.today()", "smell_explanation": "DateHelper contains a single static method that wraps datetime.date.today() \u2014 a one-liner from the standard library. The class adds zero logic and must be imported and remembered by callers.", "refactoring_suggestion": "Delete DateHelper. Call datetime.date.today() directly. If a module-level alias is needed for mocking in tests, use unittest.mock.patch('datetime.date.today') rather than an intermediate class.", "difficulty": "beginner"}
{"id": "fcdbb74625bd89ca", "language": "javascript", "smell_type": "lazy_class", "severity": "low", "code_snippet": "class MathUtils {\n static square(x) { return x * x; }\n}", "smell_explanation": "A class containing one static method that wraps x * x \u2014 a trivial expression that any caller can write inline. The class is a thin container for a single arithmetic operation.", "refactoring_suggestion": "Delete MathUtils. Use x * x or Math.pow(x, 2) inline. Export a named function (export const square = x => x * x) only if the operation is genuinely reused and complex enough to warrant naming.", "difficulty": "beginner"}
{"id": "8dc94076008d5797", "language": "java", "smell_type": "lazy_class", "severity": "low", "code_snippet": "public class Constants {\n public static final String APP_NAME = \"MyApp\";\n}", "smell_explanation": "A class that holds a single public static final field. Java historically used constant classes as namespaces, but a single-field class is overhead for a value that belongs in the class that uses it or in a richer settings object.", "refactoring_suggestion": "If APP_NAME is used in exactly one place, define it there. If it is used broadly, consider a configuration object (AppConfig.getName()) or a proper constants interface. A class with one field signals a missing home for the constant.", "difficulty": "beginner"}
{"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": "953d6d5ed54fa432", "language": "python", "smell_type": "alternative_classes", "severity": "medium", "code_snippet": "# Two modules, both logging errors differently\nclass AppLogger:\n def log_error(self, message, exc=None): ...\n def log_warning(self, message): ...\n def log_info(self, message): ...\n\nclass ServiceLogger:\n def error(self, msg, exception=None): ...\n def warn(self, msg): ...\n def info(self, msg): ...", "smell_explanation": "Two logger classes do the same job with different method names (log_error vs error, log_warning vs warn). Callers cannot swap one for the other without code changes, and new contributors must learn which to use.", "refactoring_suggestion": "Consolidate behind a single Logger interface (or ABC): def error(msg, exc=None), def warn(msg), def info(msg). Pick one naming convention; retire or alias the other. Standard library logging module is often the right answer.", "difficulty": "beginner"}
{"id": "7132ec1590bc08c8", "language": "go", "smell_type": "alternative_classes", "severity": "medium", "code_snippet": "// auth package\ntype TokenValidator struct{}\nfunc (v TokenValidator) ValidateJWT(token string) (Claims, error) { ... }\n\n// middleware package\ntype JWTChecker struct{}\nfunc (c JWTChecker) CheckToken(jwt string) (*Payload, error) { ... }", "smell_explanation": "Two structs in different packages validate JWTs with identical logic but different method and type names. Callers cannot use them interchangeably; bugs fixed in one are not reflected in the other.", "refactoring_suggestion": "Define a single TokenValidator interface in a shared package: type TokenValidator interface { Validate(token string) (*Claims, error) }. One implementation; both packages import the interface. Eliminate the duplicate.", "difficulty": "intermediate"}
{"id": "4fd5b3e84e6378e1", "language": "java", "smell_type": "alternative_classes", "severity": "high", "code_snippet": "// In order module\npublic interface PaymentGateway {\n boolean processPayment(String token, double amount, String currency);\n}\n\n// In billing module\npublic interface PaymentProvider {\n PaymentResult charge(PaymentRequest request);\n}\n\n// Both implemented by StripeAdapter and PaypalAdapter in each module", "smell_explanation": "Two interfaces representing the same concept (a payment gateway) with different APIs. StripeAdapter and PaypalAdapter are implemented twice, causing maintenance debt every time payment logic changes.", "refactoring_suggestion": "Define one canonical PaymentGateway interface in a shared module with a PaymentRequest/PaymentResult DTO. Both order and billing modules depend on the shared interface. Remove the duplicate PaymentProvider.", "difficulty": "advanced"}
{"id": "8b77abe044643b07", "language": "typescript", "smell_type": "alternative_classes", "severity": "medium", "code_snippet": "// auth/types.ts\ninterface UserSession {\n userId: string;\n token: string;\n expiresAt: number;\n}\n\n// api/types.ts\ninterface AuthToken {\n user_id: string;\n access_token: string;\n expires_at: number; // same semantics, different naming convention\n}", "smell_explanation": "Two interfaces model the same concept (an authenticated session) with camelCase vs snake_case field names. Code that flows from auth to api requires manual field mapping, introducing translation bugs.", "refactoring_suggestion": "Define one canonical AuthSession interface in a shared types package. The API layer uses a DTO adapter only at the boundary (e.g., converting to/from JSON). Internal code uses one type.", "difficulty": "beginner"}
{"id": "f99958025f1aa1e0", "language": "python", "smell_type": "incomplete_library", "severity": "medium", "code_snippet": "import re\n\ndef is_valid_email(email: str) -> bool:\n pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$'\n return bool(re.match(pattern, email))\n\ndef is_valid_url(url: str) -> bool:\n pattern = r'^https?://[^\\s/$.?#].[^\\s]*$'\n return bool(re.match(pattern, url))\n\ndef is_valid_phone(phone: str) -> bool:\n pattern = r'^\\+?[1-9]\\d{7,14}$'\n return bool(re.match(pattern, phone))", "smell_explanation": "Home-rolled regex validators for email, URL, and phone. Email regex is known to be subtly wrong for edge cases (IDN, new TLDs). The `email-validator` and `validators` libraries handle these correctly with RFC compliance.", "refactoring_suggestion": "Use email-validator (pip install email-validator) for email: from email_validator import validate_email. Use urllib.parse.urlparse for URL structure checks. Use phonenumbers library for phone validation. Don't reinvent established validators.", "difficulty": "intermediate"}
{"id": "31d17158834026b2", "language": "javascript", "smell_type": "incomplete_library", "severity": "medium", "code_snippet": "function formatDate(date) {\n const d = new Date(date);\n const year = d.getFullYear();\n const month = String(d.getMonth() + 1).padStart(2, '0');\n const day = String(d.getDate()).padStart(2, '0');\n const hours = String(d.getHours()).padStart(2, '0');\n const minutes = String(d.getMinutes()).padStart(2, '0');\n return `${year}-${month}-${day} ${hours}:${minutes}`;\n}", "smell_explanation": "Manual date formatting with six intermediate variables for a common ISO-like format. The Intl.DateTimeFormat API (built into V8/Node) or date-fns provides this in one line with locale and timezone awareness.", "refactoring_suggestion": "Use Intl.DateTimeFormat or date-fns/format: import { format } from 'date-fns'; return format(new Date(date), 'yyyy-MM-dd HH:mm'). If only ISO strings are needed: new Date(date).toISOString().slice(0, 16).replace('T', ' ').", "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": "2d0c256afaf32b20", "language": "go", "smell_type": "incomplete_library", "severity": "medium", "code_snippet": "func Contains(slice []string, target string) bool {\n for _, s := range slice {\n if s == target {\n return true\n }\n }\n return false\n}\n\nfunc Unique(slice []string) []string {\n seen := map[string]struct{}{}\n var result []string\n for _, s := range slice {\n if _, ok := seen[s]; !ok {\n seen[s] = struct{}{}\n result = append(result, s)\n }\n }\n return result\n}", "smell_explanation": "Generic slice helpers that reimport patterns developers write from memory in Go. As of Go 1.21, slices.Contains and maps.Keys are in the standard library. The two-loop patterns are well-known but not worth maintaining as custom functions.", "refactoring_suggestion": "Use slices.Contains(slice, target) from the slices package (Go 1.21+). For Unique, the set-based pattern is still manual but belongs at the call site unless shared widely. Replace Contains immediately; evaluate Unique per usage.", "difficulty": "beginner"}
{"id": "fc873095e83035f1", "language": "python", "smell_type": "message_chains", "severity": "medium", "code_snippet": "def get_invoice_currency(company_id):\n return (CompanyRegistry.get_instance()\n .find_company(company_id)\n .get_billing_account()\n .get_payment_settings()\n .get_preferred_currency()\n .get_code())", "smell_explanation": "A six-step chain navigating CompanyRegistry \u2192 Company \u2192 BillingAccount \u2192 PaymentSettings \u2192 Currency \u2192 code. Any intermediate method returning None causes an AttributeError, and any refactoring of intermediate types ripples to this call.", "refactoring_suggestion": "Apply Tell, Don't Ask: add Company.billing_currency_code() that encapsulates the traversal. The caller asks for the currency code, not for intermediate objects. This also gives Company the right place to handle missing billing accounts.", "difficulty": "intermediate"}
{"id": "ac6657eaf966ad9f", "language": "javascript", "smell_type": "message_chains", "severity": "medium", "code_snippet": "const zip = req.body.user.profile.address.location.postalCode;\nconst taxRate = req.body.user.profile.address.location.country.taxConfig.defaultRate;", "smell_explanation": "Two 6-7 level chains into a nested request body. Any missing object in the chain throws a TypeError. The code is brittle to API schema changes and impossible to test without constructing deeply nested mock objects.", "refactoring_suggestion": "Use optional chaining and provide defaults: req.body?.user?.profile?.address?.location?.postalCode ?? ''. For business logic, extract the relevant fields into a flat DTO at the controller layer: const { postalCode, country } = parseUserLocation(req.body).", "difficulty": "beginner"}
{"id": "0321e53c93d98127", "language": "typescript", "smell_type": "message_chains", "severity": "high", "code_snippet": "function applyDiscount(context: RequestContext): number {\n return context\n .getSession()\n .getCurrentUser()\n .getSubscription()\n .getPlan()\n .getDiscountPolicy()\n .calculateDiscount(context.getCart().getTotalAmount());\n}", "smell_explanation": "A 7-deep chain crosses five domain objects to reach a discount calculation. The function depends on the shape of five intermediate types, is impossible to unit-test without a full context graph, and violates the Law of Demeter severely.", "refactoring_suggestion": "Move calculateDiscount to a DiscountService that accepts (userId, planId, cartTotal) \u2014 or to User.calculateDiscount(cartTotal) if discount is user-scoped. The function should ask for the result, not traverse the object graph to compute it.", "difficulty": "advanced"}
{"id": "31744f786c1bba23", "language": "java", "smell_type": "message_chains", "severity": "medium", "code_snippet": "String city = order\n .getCustomer()\n .getShippingAddress()\n .getRegion()\n .getCity()\n .getName();", "smell_explanation": "Five chained getters across four domain objects. The chain is fragile to null returns at any level and couples the caller to the navigation path through Customer, Address, Region, and City.", "refactoring_suggestion": "Add Order.getShippingCity() which handles the traversal and null-safety internally. Callers ask the order, not the object graph: String city = order.getShippingCity(). Apply Demeter's Law: only talk to immediate collaborators.", "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": "18937bc629a120e7", "language": "python", "smell_type": "speculative_generality", "severity": "medium", "code_snippet": "class BaseHandler(ABC):\n @abstractmethod\n def handle(self, request): pass\n\n @abstractmethod\n def handle_async(self, request): pass\n\n @abstractmethod\n def handle_batch(self, requests): pass\n\n @abstractmethod\n def validate(self, request): pass\n\n @abstractmethod\n def pre_process(self, request): pass\n\n @abstractmethod\n def post_process(self, result): pass", "smell_explanation": "An abstract base class with six required methods, but only one concrete subclass exists (SyncHandler) and it raises NotImplementedError for handle_async, handle_batch, pre_process, and post_process. Speculative generality masquerading as a framework.", "refactoring_suggestion": "Define only the interface you need now: class Handler(ABC): def handle(self, request): pass. Add handle_async when an async handler is needed; add pre_process when a processing pipeline is actually built. YAGNI.", "difficulty": "intermediate"}
{"id": "7a09202d0cb526ce", "language": "javascript", "smell_type": "speculative_generality", "severity": "low", "code_snippet": "class EventEmitter {\n constructor(options = {}) {\n this.maxListeners = options.maxListeners || 10;\n this.wildcard = options.wildcard || false; // unused\n this.delimiter = options.delimiter || ':'; // unused\n this.newListener = options.newListener || false; // unused\n this.removeListener = options.removeListener || false; // unused\n }\n}", "smell_explanation": "The constructor accepts five configuration options, but only maxListeners is read by the rest of the class. The other four options were added speculatively; they do nothing and confuse users of the API.", "refactoring_suggestion": "Remove the four unused options. If wildcard or delimiter support is added later, introduce them with an actual implementation. Unused options in a constructor API set false expectations and become legacy baggage.", "difficulty": "beginner"}
{"id": "37d5c76f2b8ecd4e", "language": "java", "smell_type": "speculative_generality", "severity": "medium", "code_snippet": "public interface NotificationSender<T extends Notification, R extends SendResult> {\n R send(T notification) throws NotificationException;\n R sendWithRetry(T notification, RetryPolicy policy) throws NotificationException;\n List<R> sendBatch(List<T> notifications) throws NotificationException;\n void schedule(T notification, Instant when) throws NotificationException;\n NotificationStatus getStatus(String notificationId) throws NotificationException;\n}", "smell_explanation": "A five-method generic interface with two type parameters, but only send() is implemented by the single concrete class (EmailSender). sendWithRetry, sendBatch, schedule, and getStatus throw UnsupportedOperationException.", "refactoring_suggestion": "Start with interface NotificationSender { void send(Notification n); }. Introduce retry logic via a decorator (RetryingNotificationSender) when needed; batch and scheduling are infrastructure concerns added when requirements arrive.", "difficulty": "intermediate"}
{"id": "901aa2a9cc554047", "language": "python", "smell_type": "switch_statements", "severity": "medium", "code_snippet": "def format_value(value, fmt_type):\n if fmt_type == 'currency':\n return f'${value:,.2f}'\n elif fmt_type == 'percentage':\n return f'{value:.1f}%'\n elif fmt_type == 'integer':\n return f'{int(value):,}'\n elif fmt_type == 'decimal':\n return f'{value:.4f}'\n elif fmt_type == 'scientific':\n return f'{value:.2e}'\n else:\n return str(value)", "smell_explanation": "A chain of elif branches on fmt_type that will grow every time a new format is added. The same pattern is duplicated in display, export, and reporting code with slight variations, causing inconsistency.", "refactoring_suggestion": "Use a dispatch dict: FORMATTERS = {'currency': lambda v: f'${v:,.2f}', 'percentage': lambda v: f'{v:.1f}%', ...}. format_value(value, fmt_type) returns FORMATTERS.get(fmt_type, str)(value). New formats are data, not code branches.", "difficulty": "beginner"}
{"id": "f2e561919f4e811a", "language": "typescript", "smell_type": "switch_statements", "severity": "medium", "code_snippet": "function getStatusLabel(status: string): string {\n switch (status) {\n case 'pending': return 'Awaiting Payment';\n case 'paid': return 'Payment Received';\n case 'shipped': return 'In Transit';\n case 'delivered': return 'Delivered';\n case 'cancelled': return 'Cancelled';\n case 'refunded': return 'Refunded';\n default: return 'Unknown';\n }\n}", "smell_explanation": "A switch mapping string status codes to display labels. New statuses require touching this function, and the mapping is duplicated in CSS classes, badge colors, and filter options with subtly different keys.", "refactoring_suggestion": "Centralise as a const STATUS_LABELS: Record<OrderStatus, string> = { pending: 'Awaiting Payment', ... }. Use an OrderStatus enum to get type-safety. Other maps (CSS classes, colors) can share the same keys.", "difficulty": "beginner"}
{"id": "751e0a990583a4b0", "language": "go", "smell_type": "switch_statements", "severity": "medium", "code_snippet": "func handleEvent(eventType string, payload []byte) error {\n switch eventType {\n case \"user.created\":\n return handleUserCreated(payload)\n case \"user.deleted\":\n return handleUserDeleted(payload)\n case \"order.placed\":\n return handleOrderPlaced(payload)\n case \"order.shipped\":\n return handleOrderShipped(payload)\n case \"payment.received\":\n return handlePaymentReceived(payload)\n default:\n return fmt.Errorf(\"unknown event: %s\", eventType)\n }\n}", "smell_explanation": "A switch on event type strings that grows with every new event. Adding a handler requires modifying this function, risking merge conflicts in a busy event-driven system.", "refactoring_suggestion": "Use a handler registry: type Handler func([]byte) error; handlers := map[string]Handler{\"user.created\": handleUserCreated, ...}. handleEvent looks up handlers[eventType] and calls it. New events are registered, not hardcoded.", "difficulty": "intermediate"}
{"id": "7efe9f7f0fabcead", "language": "python", "smell_type": "temporary_field", "severity": "medium", "code_snippet": "class QueryBuilder:\n def __init__(self):\n self._table = None\n self._conditions = None\n self._columns = None\n self._limit = None\n\n def build(self, table, conditions, columns, limit=None):\n self._table = table\n self._conditions = conditions\n self._columns = columns\n self._limit = limit\n sql = f\"SELECT {', '.join(self._columns)} FROM {self._table}\"\n if self._conditions:\n sql += f\" WHERE {' AND '.join(self._conditions)}\"\n if self._limit:\n sql += f\" LIMIT {self._limit}\"\n return sql", "smell_explanation": "Four instance fields are assigned at the start of build() and used only within that call. They are None before and after build() \u2014 classic temporary fields that belong as local variables.", "refactoring_suggestion": "Make build() use local variables directly: sql = f\"SELECT {', '.join(columns)} FROM {table}\". If helpers are extracted, pass them as function parameters. No instance state is needed.", "difficulty": "beginner"}
{"id": "04e7248070897606", "language": "javascript", "smell_type": "temporary_field", "severity": "medium", "code_snippet": "class PDFExporter {\n constructor(template) {\n this.template = template;\n this.currentPage = null; // set only during export()\n this.pageBuffer = null; // set only during export()\n this.fontCache = null; // set only during export()\n }\n\n async export(document) {\n this.currentPage = 1;\n this.pageBuffer = [];\n this.fontCache = await loadFonts(this.template.fonts);\n // ... render pages using this.currentPage, this.pageBuffer, this.fontCache\n return this.pageBuffer.join('');\n }\n}", "smell_explanation": "currentPage, pageBuffer, and fontCache are null before export() is called and after it returns. They exist solely to avoid passing locals between rendering helpers \u2014 indicating missing abstraction.", "refactoring_suggestion": "Extract an ExportContext { currentPage, pageBuffer, fontCache } created at the start of export() and passed to helpers. PDFExporter remains stateless except for template, making it safe to export() concurrently.", "difficulty": "intermediate"}
{"id": "b32e64adabb64341", "language": "python", "smell_type": "data_clumps", "severity": "high", "code_snippet": "def create_employee(first_name, last_name, email, phone,\n street, city, state, postal_code, country,\n department, title, start_date, salary, currency):\n ...\n\ndef update_employee(employee_id, first_name, last_name, email, phone,\n street, city, state, postal_code, country,\n department, title, salary, currency):\n ...", "smell_explanation": "Fourteen primitive parameters, with three obvious clumps: name (first+last), address (street+city+state+postal+country), and compensation (salary+currency). Every signature change ripples to all callers.", "refactoring_suggestion": "Introduce PersonName(first, last), Address(street, city, state, postal_code, country), and Money(amount, currency) value objects. create_employee(name: PersonName, contact: ContactInfo, address: Address, role: RoleInfo, comp: Money).", "difficulty": "intermediate"}
{"id": "dbc4f64ac35a7d24", "language": "typescript", "smell_type": "data_clumps", "severity": "medium", "code_snippet": "async function fetchWeather(\n lat: number,\n lng: number,\n unit: 'celsius' | 'fahrenheit',\n lang: string,\n apiKey: string\n): Promise<WeatherData> { ... }\n\nasync function fetchForecast(\n lat: number,\n lng: number,\n days: number,\n unit: 'celsius' | 'fahrenheit',\n lang: string,\n apiKey: string\n): Promise<ForecastData> { ... }", "smell_explanation": "lat + lng always appear as a pair (a geographic coordinate); unit + lang are always passed together as display preferences. Both clumps appear in every weather API call.", "refactoring_suggestion": "Define Coordinate { lat: number; lng: number } and WeatherPrefs { unit: 'celsius' | 'fahrenheit'; lang: string }. fetchWeather(location: Coordinate, prefs: WeatherPrefs, apiKey: string) is cleaner and prevents lat/lng transposition bugs.", "difficulty": "beginner"}
{"id": "b96dc1892fe915b2", "language": "go", "smell_type": "data_clumps", "severity": "medium", "code_snippet": "func LogRequest(method, path, clientIP string, statusCode, durationMs int) {\n log.Printf(\"[%s] %s from %s -> %d in %dms\", method, path, clientIP, statusCode, durationMs)\n}\n\nfunc RecordMetric(method, path, clientIP string, statusCode, durationMs int) {\n metrics.Record(method, path, clientIP, statusCode, durationMs)\n}\n\nfunc StoreAccessLog(method, path, clientIP string, statusCode, durationMs int) {\n db.Exec(\"INSERT INTO access_log VALUES (?,?,?,?,?)\", method, path, clientIP, statusCode, durationMs)\n}", "smell_explanation": "The same five parameters appear in every request observability function. The clump (method, path, clientIP, statusCode, durationMs) represents a RequestEvent concept that is missing from the type system.", "refactoring_suggestion": "Define type RequestEvent struct { Method, Path, ClientIP string; Status, DurationMs int }. All three functions accept RequestEvent. Callers construct one event and pass it everywhere; adding fields (e.g., TraceID) requires one change.", "difficulty": "beginner"}
{"id": "2d2c145bc18fcecb", "language": "java", "smell_type": "feature_envy", "severity": "high", "code_snippet": "public class InvoicePrinter {\n public String print(Invoice invoice) {\n double subtotal = invoice.getLineItems().stream()\n .mapToDouble(li -> li.getQuantity() * li.getUnitPrice()).sum();\n double tax = subtotal * invoice.getTaxRate();\n double total = subtotal + tax - invoice.getDiscountAmount();\n String itemsText = invoice.getLineItems().stream()\n .map(li -> li.getProductName() + \" x\" + li.getQuantity() + \" @ \" + li.getUnitPrice())\n .collect(Collectors.joining(\"\n\"));\n return String.format(\"Items:\n%s\nSubtotal: %.2f\nTax: %.2f\nTotal: %.2f\",\n itemsText, subtotal, tax, total);\n }\n}", "smell_explanation": "InvoicePrinter reaches into Invoice's lineItems, taxRate, discountAmount, product names, quantities, and unit prices to compute subtotal, tax, and total \u2014 all logic that belongs on Invoice itself.", "refactoring_suggestion": "Add invoice.subtotal(), invoice.taxAmount(), invoice.total(), and invoice.lineItemDescriptions() methods. InvoicePrinter.print() becomes a formatting function that calls these, delegating all financial logic to Invoice.", "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": "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": "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": "9d0ab3cdbf01c4e5", "language": "python", "smell_type": "inappropriate_intimacy", "severity": "medium", "code_snippet": "class AnalyticsCollector:\n def __init__(self, session_store):\n self.store = session_store\n\n def record_event(self, user_id, event_name):\n # Reaches into session_store private implementation\n session = self.store._active_sessions.get(user_id)\n if session and session._raw_data.get('tracking_enabled'):\n self.store._event_log.append({\n 'user': user_id,\n 'event': event_name,\n 'session_id': session._sid\n })", "smell_explanation": "AnalyticsCollector accesses _active_sessions, _raw_data, _event_log, and _sid \u2014 four private members across two objects. Any internal refactoring of SessionStore will silently break analytics.", "refactoring_suggestion": "SessionStore should expose: is_tracking_enabled(user_id) -> bool and log_event(user_id, event_name, session_id) -> None. AnalyticsCollector calls these public methods only.", "difficulty": "intermediate"}
{"id": "0a6c0c70d8b72985", "language": "python", "smell_type": "refused_bequest", "severity": "high", "code_snippet": "class Shape:\n def area(self): raise NotImplementedError\n def perimeter(self): raise NotImplementedError\n def volume(self): raise NotImplementedError # 3D only\n def surface_area(self): raise NotImplementedError # 3D only\n\nclass Circle(Shape):\n def __init__(self, r): self.r = r\n def area(self): return 3.14159 * self.r ** 2\n def perimeter(self): return 2 * 3.14159 * self.r\n def volume(self): raise TypeError(\"Circle has no volume\")\n def surface_area(self): raise TypeError(\"Circle has no surface area\")\n\nclass Sphere(Shape):\n def __init__(self, r): self.r = r\n def area(self): raise TypeError(\"Sphere area is ambiguous \u2014 use surface_area()\")\n def perimeter(self): raise TypeError(\"Sphere has no perimeter\")\n def volume(self): return (4/3) * 3.14159 * self.r ** 3\n def surface_area(self): return 4 * 3.14159 * self.r ** 2", "smell_explanation": "Shape defines both 2D and 3D interfaces. Circle refuses volume() and surface_area(); Sphere refuses perimeter() and area(). Both subclasses throw exceptions for inherited methods \u2014 a textbook Refused Bequest + LSP violation.", "refactoring_suggestion": "Separate: class Shape2D(ABC): area(), perimeter(); class Shape3D(ABC): volume(), surface_area(). Circle(Shape2D); Sphere(Shape3D). No subclass inherits methods it cannot implement.", "difficulty": "intermediate"}
{"id": "e6e4875a29b8a03c", "language": "go", "smell_type": "refused_bequest", "severity": "medium", "code_snippet": "type Storage interface {\n Read(key string) ([]byte, error)\n Write(key string, data []byte) error\n Delete(key string) error\n Lock(key string) error // only meaningful for distributed storage\n Unlock(key string) error // only meaningful for distributed storage\n}\n\ntype InMemoryStore struct{ data map[string][]byte }\n\nfunc (s *InMemoryStore) Read(key string) ([]byte, error) { return s.data[key], nil }\nfunc (s *InMemoryStore) Write(key string, d []byte) error { s.data[key] = d; return nil }\nfunc (s *InMemoryStore) Delete(key string) error { delete(s.data, key); return nil }\nfunc (s *InMemoryStore) Lock(key string) error { return errors.New(\"not supported\") }\nfunc (s *InMemoryStore) Unlock(key string) error { return errors.New(\"not supported\") }", "smell_explanation": "InMemoryStore must implement Lock and Unlock from Storage but returns errors \u2014 Refused Bequest. Callers cannot safely call Lock() on any Storage without checking the concrete type.", "refactoring_suggestion": "Segregate: type Storage interface { Read, Write, Delete }. type DistributedStorage interface { Storage; Lock, Unlock }. InMemoryStore implements Storage only. Callers that need locking accept DistributedStorage explicitly.", "difficulty": "intermediate"}
{"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": "a6593d52f8b3cd72", "language": "java", "smell_type": "parallel_inheritance", "severity": "high", "code_snippet": "// Adding a new report type requires changes to THREE hierarchies:\nabstract class Report { abstract String generate(); }\nclass SalesReport extends Report { String generate() { ... } }\nclass InventoryReport extends Report { String generate() { ... } }\n\nabstract class ReportExporter { abstract void export(Report r); }\nclass SalesReportExporter extends ReportExporter { void export(Report r) { ... } }\nclass InventoryReportExporter extends ReportExporter { void export(Report r) { ... } }\n\nabstract class ReportScheduler { abstract void schedule(Report r); }\nclass SalesReportScheduler extends ReportScheduler { void schedule(Report r) { ... } }\nclass InventoryReportScheduler extends ReportScheduler { void schedule(Report r) { ... } }", "smell_explanation": "Three parallel class hierarchies (Report, Exporter, Scheduler) grow lockstep \u2014 adding a new report type requires three new subclasses. This is a clear Parallel Inheritance Hierarchies smell.", "refactoring_suggestion": "Merge via composition: interface Report { String generate(); void export(Exporter e); void schedule(Scheduler s); } or use the Visitor pattern. Alternatively, make export() and schedule() generic operations that accept a Report object, eliminating the need for report-specific subclasses.", "difficulty": "advanced"}
{"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": "5f92a45b153703de", "language": "go", "smell_type": "dead_code", "severity": "medium", "code_snippet": "package config\n\n// loadFromFile reads config from a JSON file.\n// Deprecated: use LoadFromEnv instead. Kept for local development.\nfunc loadFromFile(path string) (*Config, error) {\n // 40 lines of JSON parsing...\n}\n\n// debugDumpConfig prints all config values.\n// Remove before release - left in for debugging.\nfunc debugDumpConfig(c *Config) {\n fmt.Printf(\"%+v\n\", c)\n}", "smell_explanation": "A deprecated file-based loader and a debug-dump function marked 'remove before release' are still in production code. The deprecation comment implies loadFromFile is still used; the debug comment implies debugDumpConfig was already meant to be deleted.", "refactoring_suggestion": "Delete both functions. If loadFromFile is still needed in development, gate it with a build tag (//go:build dev). Debug dump utility can be replaced by log.Printf or a test helper. Remove 'Deprecated:' comments that describe code rather than guide users.", "difficulty": "beginner"}
{"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"}
{"id": "f5dde190370b64d7", "language": "python", "smell_type": "god_object", "severity": "medium", "code_snippet": "class Bot:\n def __init__(self):\n self.discord_client = None\n self.db = None\n self.scheduler = None\n self.config = {}\n self.active_games = {}\n self.leaderboard = {}\n self.voice_connections = {}\n\n def on_message(self, msg): ...\n def on_join(self, member): ...\n def start_game(self, channel): ...\n def end_game(self, channel): ...\n def update_score(self, user, pts): ...\n def get_leaderboard(self): ...\n def schedule_event(self, event, when): ...\n def connect_voice(self, channel): ...\n def play_audio(self, file): ...\n def fetch_weather(self, city): ...\n def run_db_backup(self): ...\n def reload_config(self): ...", "smell_explanation": "A Discord bot class that owns the client, database, scheduler, game state, leaderboard, voice connections, and implements 12+ methods across event handling, game logic, audio, external APIs, and ops. Every feature change touches Bot.", "refactoring_suggestion": "Decompose: GameManager (active_games, start/end/score), LeaderboardService, VoiceManager (voice + audio), EventScheduler, and infrastructure adapters. Bot becomes a thin dispatcher wiring them together via events.", "difficulty": "intermediate"}
{"id": "3b4b28f2f61f7334", "language": "java", "smell_type": "god_object", "severity": "high", "code_snippet": "@RestController\n@Service\n@Repository\npublic class UserController {\n @Autowired private EntityManager em;\n @Autowired private JavaMailSender mailer;\n @Autowired private BCryptPasswordEncoder encoder;\n\n @PostMapping(\"/register\")\n public ResponseEntity<?> register(@RequestBody UserDto dto) {\n // Validates, hashes password, persists, sends welcome email \u2014 all inline\n User u = new User(dto.name(), encoder.encode(dto.password()), dto.email());\n em.persist(u);\n mailer.send(buildWelcomeEmail(u));\n return ResponseEntity.ok(u.getId());\n }\n // 30 more methods mixing HTTP, DB, and email logic\n}", "smell_explanation": "A single class annotated as @RestController, @Service, and @Repository simultaneously. It owns HTTP handling, business logic, data access, and email \u2014 all Spring layers collapsed into one class.", "refactoring_suggestion": "Follow Spring layering: UserController (HTTP only) \u2192 UserService (business logic + transactions) \u2192 UserRepository (JPA/DB). Email lives in a NotificationService. Each layer has its own @Component stereotype and dependency direction.", "difficulty": "intermediate"}