File size: 81,050 Bytes
33078b7 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | {"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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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": "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"}
{"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": "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": "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": "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": "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": "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"}
|