id stringlengths 16 16 | language stringclasses 6
values | smell_type stringlengths 4 22 | severity stringclasses 4
values | code_snippet stringlengths 56 1.54k | smell_explanation stringlengths 165 252 | refactoring_suggestion stringlengths 65 320 | difficulty stringclasses 3
values |
|---|---|---|---|---|---|---|---|
7c2357c947e69522 | rust | speculative_generality | medium | pub trait Processor<I, O, E, C = ()> {
type Config: Default;
fn process(&self, input: I, config: Option<C>) -> Result<O, E>;
fn process_batch(&self, inputs: Vec<I>, config: Option<C>) -> Vec<Result<O, E>>;
fn validate(&self, input: &I) -> bool;
fn transform(&self, output: O) -> O;
fn on_error(&s... | A five-method generic trait with four type parameters where the entire codebase contains a single impl β EmailProcessor β that uses only process() and ignores process_batch, transform, and on_error with no-op defaults. Over-abstracted for one use case. | 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. | advanced |
18937bc629a120e7 | python | speculative_generality | medium | class BaseHandler(ABC):
@abstractmethod
def handle(self, request): pass
@abstractmethod
def handle_async(self, request): pass
@abstractmethod
def handle_batch(self, requests): pass
@abstractmethod
def validate(self, request): pass
@abstractmethod
def pre_process(self, request... | 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. | 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. | intermediate |
f2e561919f4e811a | typescript | switch_statements | medium | function getStatusLabel(status: string): string {
switch (status) {
case 'pending': return 'Awaiting Payment';
case 'paid': return 'Payment Received';
case 'shipped': return 'In Transit';
case 'delivered': return 'Delivered';
case 'cancelled': return 'Cancelled';
case 'refunded':... | 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. | 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. | beginner |
44ff65890e33fb45 | python | message_chains | medium | def get_city(user):
return user.get_profile().get_address().get_location().get_city()
# called as:
city = order.get_customer().get_profile().get_address().get_location().get_city() | The message chain navigates five objects deep (customer β profile β address β location β city). Any intermediate object returning None causes an AttributeError; refactoring any intermediate class ripples everywhere. | 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. | intermediate |
4fd5b3e84e6378e1 | java | alternative_classes | high | // In order module
public interface PaymentGateway {
boolean processPayment(String token, double amount, String currency);
}
// In billing module
public interface PaymentProvider {
PaymentResult charge(PaymentRequest request);
}
// Both implemented by StripeAdapter and PaypalAdapter in each module | 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. | 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. | advanced |
106472d7ff00d631 | javascript | parallel_inheritance | medium | // Every new payment provider requires additions in THREE places:
class PaymentProcessor { process() {} }
class StripeProcessor extends PaymentProcessor { process() {} }
class PaypalProcessor extends PaymentProcessor { process() {} }
class PaymentLogger { log() {} }
class StripeLogger extends PaymentLogger { log() {} ... | 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. | Merge into a single PaymentProvider interface: { process(), log(), validate() }. StripeProvider implements all three; PaypalProvider implements all three. One class per provider, one hierarchy. | intermediate |
011f2d8c44970ff2 | python | god_object | high | class Application:
def __init__(self):
self.users = []
self.orders = []
self.products = []
self.db_conn = None
self.email_client = None
self.cache = {}
self.logger = None
self.config = {}
def create_user(self, name, email): ...
def delete_user... | 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. | Decompose into bounded-context classes: UserService, OrderService, ProductService, NotificationService, and infrastructure adapters (DatabaseAdapter, CacheAdapter). Wire them via dependency injection rather than a single monolith. | intermediate |
2d0c256afaf32b20 | go | incomplete_library | medium | func Contains(slice []string, target string) bool {
for _, s := range slice {
if s == target {
return true
}
}
return false
}
func Unique(slice []string) []string {
seen := map[string]struct{}{}
var result []string
for _, s := range slice {
if _, ok := seen[s... | 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. | 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. | beginner |
0d9ce3be63cb0499 | javascript | none | none | class ShoppingCart {
constructor() {
this.items = [];
}
addItem(product, quantity) {
const existing = this.items.find(i => i.product.id === product.id);
if (existing) {
existing.quantity += quantity;
} else {
this.items.push({ product, quantity });
}
}
get total() {
retur... | 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. | No refactoring needed. The class is a good example of a focused, cohesive value object. | beginner |
37d5c76f2b8ecd4e | java | speculative_generality | medium | public interface NotificationSender<T extends Notification, R extends SendResult> {
R send(T notification) throws NotificationException;
R sendWithRetry(T notification, RetryPolicy policy) throws NotificationException;
List<R> sendBatch(List<T> notifications) throws NotificationException;
void schedule(... | 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. | 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. | intermediate |
4587ead1f94ede37 | go | middle_man | medium | type CacheService struct {
client *redis.Client
}
func (c *CacheService) Get(key string) (string, error) { return c.client.Get(ctx, key).Result() }
func (c *CacheService) Set(key, value string, ttl time.Duration) error { return c.client.Set(ctx, key, value, ttl).Err() }
func (c *CacheService) Delete(key string... | 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. | 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. | intermediate |
060fecc4469ed2a9 | javascript | long_method | high | async function handleCheckout(req, res) {
try {
const { userId, cartId, couponCode, shippingAddress, paymentToken } = req.body;
const user = await User.findById(userId);
if (!user) return res.status(404).json({ error: 'User not found' });
const cart = await Cart.findById(cartId).populate('items.produc... | 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. | 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. | intermediate |
2b4b3985eb7d888a | python | none | none | from dataclasses import dataclass
from typing import List
@dataclass(frozen=True)
class Address:
street: str
city: str
country: str
postal_code: str
def __post_init__(self):
if not self.postal_code:
raise ValueError("postal_code required")
if len(self.country) != 2:
... | Clean value objects: Address is frozen (immutable) with self-validating __post_init__, Order is a mutable aggregate with a derived property. No smell β proper data modelling with Python dataclasses. | No refactoring needed. This is idiomatic Python domain modelling. | beginner |
3c51fbe48a2724fa | java | alternative_classes | medium | // Two classes doing the same thing with different names
class CustomerEmailSender {
public void send(String to, String subject, String body) { ... }
public void sendWithAttachment(String to, String subject, String body, File attachment) { ... }
}
class UserNotificationMailer {
public void sendEmail(String... | 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. | 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. | beginner |
482efafe5f2edfac | python | comments_as_smell | medium | class Calculator:
# Initialize the calculator
def __init__(self):
# Set history to empty list
self.history = []
# Add two numbers
def add(self, a, b):
# Calculate the sum
result = a + b
# Append result to history
self.history.append(result)
# Retu... | Every statement is narrated by a comment that restates it verbatim. The class docstring and method docstrings would be appropriate places for intent β but only if there were non-obvious constraints to document (precision, overflow, etc.). | 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. | beginner |
98841ab5011051a7 | rust | long_method | high | pub fn parse_config(path: &str) -> Result<Config, ConfigError> {
let contents = std::fs::read_to_string(path)
.map_err(|e| ConfigError::Io(e))?;
let raw: serde_json::Value = serde_json::from_str(&contents)
.map_err(|e| ConfigError::Parse(e))?;
let host = raw["database"]["host"].as_str()
... | 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. | 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. | intermediate |
81da26f8bf150d05 | java | refused_bequest | high | abstract class Vehicle {
abstract void accelerate();
abstract void brake();
abstract void refuel();
abstract void fly();
}
class Car extends Vehicle {
void accelerate() { ... }
void brake() { ... }
void refuel() { ... }
void fly() { throw new UnsupportedOperationException("Cars cannot f... | Car extends Vehicle but throws UnsupportedOperationException for fly() β a Refused Bequest and Liskov Substitution Principle violation. Any code that calls vehicle.fly() will fail at runtime for Car instances. | Segregate interfaces: interface GroundVehicle { void accelerate(); void brake(); void refuel(); } interface Aircraft extends GroundVehicle { void fly(); } Car implements GroundVehicle; Airplane implements Aircraft. | intermediate |
48e1aafccfa79fdd | java | lazy_class | low | public class StringUtils {
public static String capitalize(String s) {
if (s == null || s.isEmpty()) return s;
return Character.toUpperCase(s.charAt(0)) + s.toLowerCase().substring(1);
}
} | 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. | 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. | beginner |
7132ec1590bc08c8 | go | alternative_classes | medium | // auth package
type TokenValidator struct{}
func (v TokenValidator) ValidateJWT(token string) (Claims, error) { ... }
// middleware package
type JWTChecker struct{}
func (c JWTChecker) CheckToken(jwt string) (*Payload, error) { ... } | 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. | 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. | intermediate |
e5f297007150600a | python | parallel_inheritance | medium | # Every time you add a new shape, you must add a class in TWO hierarchies:
class Shape: pass
class Circle(Shape): pass
class Rectangle(Shape): pass
class ShapeRenderer: pass
class CircleRenderer(ShapeRenderer): pass
class RectangleRenderer(ShapeRenderer): pass
class ShapeSerializer: pass
class CircleSerializer(ShapeS... | Adding a Triangle requires creating three classes: Triangle, TriangleRenderer, TriangleSerializer. The parallel hierarchies move in lockstep β a classic Parallel Inheritance smell that makes extension laborious and error-prone. | 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. | advanced |
15f4a78447a06e4f | java | long_method | high | public ResponseEntity<OrderResponse> placeOrder(PlaceOrderRequest request) {
User user = userRepo.findById(request.getUserId()).orElseThrow(() -> new NotFoundException("User not found"));
Cart cart = cartRepo.findByUserId(request.getUserId()).orElseThrow(() -> new NotFoundException("Cart empty"));
if (cart.... | 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. | 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. | intermediate |
953d6d5ed54fa432 | python | alternative_classes | medium | # Two modules, both logging errors differently
class AppLogger:
def log_error(self, message, exc=None): ...
def log_warning(self, message): ...
def log_info(self, message): ...
class ServiceLogger:
def error(self, msg, exception=None): ...
def warn(self, msg): ...
def info(self, msg): ... | 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. | 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. | beginner |
99cf7685ddb2d324 | python | large_class | high | class UserManager:
# 400+ line class
def register(self): ...
def login(self): ...
def logout(self): ...
def reset_password(self): ...
def change_email(self): ...
def update_profile(self): ...
def upload_avatar(self): ...
def get_notifications(self): ...
def mark_notification_read... | 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. | 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. | intermediate |
84e4707a4032bd4a | typescript | none | none | type Result<T, E = Error> =
| { ok: true; value: T }
| { ok: false; error: E };
function divide(a: number, b: number): Result<number, string> {
if (b === 0) return { ok: false, error: 'Division by zero' };
return { ok: true, value: a / b };
}
const result = divide(10, 2);
if (result.ok) {
console.log(result... | Clean discriminated union for error handling β no exceptions for expected failures, exhaustive type narrowing, and the happy path is explicit. The function has a single responsibility and no smell. | No refactoring needed. This is a well-typed functional pattern for recoverable errors. | intermediate |
0bd8a1a71089e3ea | rust | comments_as_smell | low | // Function to calculate factorial
fn factorial(n: u64) -> u64 {
// If n is 0 return 1
if n == 0 {
return 1; // base case
}
// Otherwise multiply n by factorial of n-1
n * factorial(n - 1)
} | 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). | 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 β not the recursion itself. | beginner |
a6593d52f8b3cd72 | java | parallel_inheritance | high | // Adding a new report type requires changes to THREE hierarchies:
abstract class Report { abstract String generate(); }
class SalesReport extends Report { String generate() { ... } }
class InventoryReport extends Report { String generate() { ... } }
abstract class ReportExporter { abstract void export(Report r); }
cl... | Three parallel class hierarchies (Report, Exporter, Scheduler) grow lockstep β adding a new report type requires three new subclasses. This is a clear Parallel Inheritance Hierarchies smell. | 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. | advanced |
2d2c145bc18fcecb | java | feature_envy | high | public class InvoicePrinter {
public String print(Invoice invoice) {
double subtotal = invoice.getLineItems().stream()
.mapToDouble(li -> li.getQuantity() * li.getUnitPrice()).sum();
double tax = subtotal * invoice.getTaxRate();
double total = subtotal + tax - invoice.getDiscount... | InvoicePrinter reaches into Invoice's lineItems, taxRate, discountAmount, product names, quantities, and unit prices to compute subtotal, tax, and total β all logic that belongs on Invoice itself. | 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. | intermediate |
09c2850421b8dffc | python | inappropriate_intimacy | high | class OrderExporter:
def __init__(self, order_service):
self.service = order_service
def export_to_csv(self, user_id):
# Directly accesses internal cache dict
orders = self.service._order_cache.get(user_id, [])
# Bypasses query method, accesses raw DB cursor
extra = list... | 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. | 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. | intermediate |
8dc94076008d5797 | java | lazy_class | low | public class Constants {
public static final String APP_NAME = "MyApp";
} | 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. | 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. | beginner |
5f08474767da64df | go | feature_envy | medium | type Formatter struct{}
func (f *Formatter) FormatUser(u *User) string {
age := time.Now().Year() - u.BirthYear
initials := string(u.FirstName[0]) + string(u.LastName[0])
status := "active"
if u.DeletedAt != nil {
status = "deleted"
}
return fmt.Sprintf("%s %s (%s, age %d) [%s]", u.Firs... | Formatter.FormatUser reaches into User's BirthYear, DeletedAt, and name fields to compute age, initials, and status β knowledge that belongs on User. Formatter is more interested in User than in its own formatting concerns. | 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()). | beginner |
7a09202d0cb526ce | javascript | speculative_generality | low | class EventEmitter {
constructor(options = {}) {
this.maxListeners = options.maxListeners || 10;
this.wildcard = options.wildcard || false; // unused
this.delimiter = options.delimiter || ':'; // unused
this.newListener = options.newListener || false; // unused
this.removeListener = op... | 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. | 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. | beginner |
ce8a82840a168acb | java | comments_as_smell | medium | // Check if user is not null and has admin role
if (user != null && user.getRole().equals("admin")) {
// Call the method to delete the resource
resourceService.delete(resourceId);
// Log that we deleted it
logger.info("Resource " + resourceId + " was deleted");
} | Every line has a comment restating what the code already says. The comment before the if-block describes the condition in plain English β information that clear variable names and method calls already convey. | 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. | beginner |
e6e4875a29b8a03c | go | refused_bequest | medium | type Storage interface {
Read(key string) ([]byte, error)
Write(key string, data []byte) error
Delete(key string) error
Lock(key string) error // only meaningful for distributed storage
Unlock(key string) error // only meaningful for distributed storage
}
type InMemoryStore struct{ data map[str... | InMemoryStore must implement Lock and Unlock from Storage but returns errors β Refused Bequest. Callers cannot safely call Lock() on any Storage without checking the concrete type. | Segregate: type Storage interface { Read, Write, Delete }. type DistributedStorage interface { Storage; Lock, Unlock }. InMemoryStore implements Storage only. Callers that need locking accept DistributedStorage explicitly. | intermediate |
321e9355abd0286c | javascript | dead_code | low | function calculateTax(amount, region) {
// Old flat-rate logic kept for reference
// const TAX_RATE = 0.08;
// return amount * TAX_RATE;
const rates = { US: 0.07, EU: 0.20, UK: 0.20 };
return amount * (rates[region] ?? 0.10);
} | Two commented-out lines of old logic are preserved 'for reference.' Commented code in version control is noise β it clutters diffs, confuses readers, and is never actually referenced because nobody knows when it was valid. | 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. | beginner |
2cfca8a54b860739 | python | lazy_class | low | class DateHelper:
@staticmethod
def today():
from datetime import date
return date.today() | DateHelper contains a single static method that wraps datetime.date.today() β a one-liner from the standard library. The class adds zero logic and must be imported and remembered by callers. | 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. | beginner |
ac6657eaf966ad9f | javascript | message_chains | medium | const zip = req.body.user.profile.address.location.postalCode;
const taxRate = req.body.user.profile.address.location.country.taxConfig.defaultRate; | 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. | 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). | beginner |
26126cacab6e5fa6 | typescript | god_object | high | class AuthManager {
private users: Map<string, User> = new Map();
private sessions: Map<string, Session> = new Map();
private tokens: Map<string, string> = new Map();
private failedAttempts: Map<string, number> = new Map();
private blockedIPs: Set<string> = new Set();
private auditLog: AuditEntry[] = [];
... | 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. | 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. | advanced |
31744f786c1bba23 | java | message_chains | medium | String city = order
.getCustomer()
.getShippingAddress()
.getRegion()
.getCity()
.getName(); | 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. | 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. | intermediate |
f5dde190370b64d7 | python | god_object | medium | class Bot:
def __init__(self):
self.discord_client = None
self.db = None
self.scheduler = None
self.config = {}
self.active_games = {}
self.leaderboard = {}
self.voice_connections = {}
def on_message(self, msg): ...
def on_join(self, member): ...
... | 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. | 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. | intermediate |
fdc902f976171a01 | java | middle_man | low | public class LoggerWrapper {
private final Logger log = LoggerFactory.getLogger(LoggerWrapper.class);
public void info(String msg) { log.info(msg); }
public void warn(String msg) { log.warn(msg); }
public void error(String msg) { log.error(msg); }
public void debug(String msg) { log.debug(msg); }... | LoggerWrapper adds nothing over the SLF4J Logger it wraps β same method signatures, no enrichment. Every class that uses it must depend on a non-standard type instead of the ubiquitous Logger. | 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. | beginner |
dbc4f64ac35a7d24 | typescript | data_clumps | medium | async function fetchWeather(
lat: number,
lng: number,
unit: 'celsius' | 'fahrenheit',
lang: string,
apiKey: string
): Promise<WeatherData> { ... }
async function fetchForecast(
lat: number,
lng: number,
days: number,
unit: 'celsius' | 'fahrenheit',
lang: string,
apiKey: string
): Promise<Forecas... | 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. | 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. | beginner |
c21794d31a85dde6 | javascript | feature_envy | medium | class OrderSummary {
constructor(order) { this.order = order; }
format() {
const items = this.order.lineItems.map(li =>
`${li.product.name} x${li.quantity} @ $${li.product.price.toFixed(2)}`
);
const tax = this.order.subtotal * this.order.taxRate;
const total = this.order.subtotal + tax - thi... | 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. | 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. | beginner |
a781a1e5f68e44c8 | rust | primitive_obsession | medium | fn send_message(
sender_id: u64,
receiver_id: u64,
content: String,
timestamp: i64,
channel: String,
) -> Result<(), String> {
if content.is_empty() {
return Err("empty content".into());
}
if timestamp < 0 {
return Err("invalid timestamp".into());
}
// ...
Ok(... | 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. | 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). | intermediate |
2d9f5e51d7dc2fe3 | typescript | data_clumps | medium | function sendInvoice(
recipientName: string,
recipientEmail: string,
recipientPhone: string,
amount: number,
currency: string,
dueDate: Date
): void { ... }
function remindInvoice(
recipientName: string,
recipientEmail: string,
recipientPhone: string,
invoiceId: string
): void { ... } | 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. | Define interface Contact { name: string; email: string; phone: string; } and pass Contact objects. Functions become sendInvoice(recipient: Contact, amount: number, currency: string, dueDate: Date). | beginner |
0a1ee9ced63f2fc3 | rust | none | none | #[derive(Debug, Clone, PartialEq)]
pub struct Temperature {
celsius: f64,
}
impl Temperature {
pub fn from_celsius(c: f64) -> Result<Self, &'static str> {
if c < -273.15 {
return Err("below absolute zero");
}
Ok(Temperature { celsius: c })
}
pub fn from_fahrenheit(f... | Clean newtype value object: private field, validated constructors, unit-converting accessors, derived traits. Represents a domain concept (temperature) with its own invariants. No smell. | No refactoring needed. This is idiomatic Rust domain modelling with proper encapsulation. | intermediate |
002fcf160adc5571 | rust | large_class | medium | pub struct Server {
config: Config,
db_pool: PgPool,
cache: RedisPool,
router: Router,
mailer: Mailer,
job_queue: Queue,
metrics: MetricsRegistry,
auth: AuthService,
}
impl Server {
pub fn new(...) -> Self { ... }
pub async fn start(&self) { ... }
pub async fn stop(&self) { ... | 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. | 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 β other concerns live in their own types. | advanced |
6f46d668792b8cf5 | typescript | primitive_obsession | medium | function createUser(
name: string,
email: string,
streetAddress: string,
city: string,
state: string,
zipCode: string,
countryCode: string,
phoneAreaCode: string,
phoneNumber: string
): User {
// email validation inline
if (!email.includes('@')) throw new Error('Invalid email');
// zip validatio... | 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. | 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. | intermediate |
8b77abe044643b07 | typescript | alternative_classes | medium | // auth/types.ts
interface UserSession {
userId: string;
token: string;
expiresAt: number;
}
// api/types.ts
interface AuthToken {
user_id: string;
access_token: string;
expires_at: number; // same semantics, different naming convention
} | 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. | 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. | beginner |
0fb4db6386940a81 | python | speculative_generality | low | class EventPublisher:
def __init__(self, strategy=None, serializer=None, retry_policy=None, middleware=None):
self.strategy = strategy or DefaultStrategy()
self.serializer = serializer or JsonSerializer()
self.retry_policy = retry_policy or NoRetry()
self.middleware = middleware or [... | The class has four pluggable strategies and publish() has five parameters, but the codebase only ever calls EventPublisher().publish(event). The generality is speculative β no current caller needs any of these extension points. | 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. | beginner |
fcdbb74625bd89ca | javascript | lazy_class | low | class MathUtils {
static square(x) { return x * x; }
} | A class containing one static method that wraps x * x β a trivial expression that any caller can write inline. The class is a thin container for a single arithmetic operation. | 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. | beginner |
448d3d9f3fd3e56a | python | temporary_field | medium | class InvoiceGenerator:
def __init__(self, order):
self.order = order
self.tax_rate = None # only set during generate()
self.line_items = None # only set during generate()
self.subtotal = None # only set during generate()
def generate(self):
self.tax_rate... | 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 β a sign the class should not own them. | 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. | intermediate |
d80130dea47f6a28 | java | none | none | public final class Email {
private final String value;
private Email(String value) { this.value = value; }
public static Email of(String value) {
if (value == null || !value.contains("@")) {
throw new IllegalArgumentException("Invalid email: " + value);
}
return new Ema... | Textbook immutable value object: validation at construction, no public constructor (factory method enforces invariants), equals/hashCode based on value. Correct, defensive, and idiomatic Java. | No refactoring needed. This is a well-implemented value object following DDD patterns. | intermediate |
751e0a990583a4b0 | go | switch_statements | medium | func handleEvent(eventType string, payload []byte) error {
switch eventType {
case "user.created":
return handleUserCreated(payload)
case "user.deleted":
return handleUserDeleted(payload)
case "order.placed":
return handleOrderPlaced(payload)
case "order.shipped":
ret... | 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. | 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. | intermediate |
b222a3a933d0de54 | python | incomplete_library | low | import csv
def write_csv(rows, filepath, encoding='utf-8'):
with open(filepath, 'w', newline='', encoding=encoding) as f:
writer = csv.DictWriter(f, fieldnames=rows[0].keys())
writer.writeheader()
writer.writerows(rows)
def read_csv(filepath, encoding='utf-8'):
with open(filepath, enco... | This wraps Python's built-in csv module with thin wrappers that add no meaningful value β the standard csv.DictWriter/DictReader API is already this simple. Wrapping it creates a non-standard interface callers must learn. | 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. | beginner |
34ebdf3cd3996658 | python | feature_envy | medium | class Report:
def __init__(self, data_source):
self.data_source = data_source
def generate(self):
records = self.data_source.records
total = sum(r.amount for r in self.data_source.records if r.status == 'paid')
overdue = [r for r in self.data_source.records if r.due_date < datet... | 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 β a classic Feature Envy. | Move the aggregation logic to DataSource as paid_total(), overdue_records(), and average_amount() methods. Report.generate() then just calls data_source.summary(). | beginner |
319ef348aea8ff1f | java | temporary_field | medium | public class ReportBuilder {
private List<String> headers; // only set in buildHeaders()
private List<Row> rows; // only set in buildRows()
private double grandTotal; // only set in buildRows()
private String currency; // only set in buildRows()
public Report build(DataSet da... | 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. | 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. | intermediate |
fab47ff85e64731a | javascript | inappropriate_intimacy | medium | class OrderProcessor {
constructor(order, inventory) {
this.order = order;
this.inventory = inventory;
}
process() {
// Directly manipulates Inventory internals
for (const item of this.order.items) {
this.inventory._stockLevels[item.sku] -= item.qty;
if (this.inventory._stockLevels[it... | 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. | 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. | intermediate |
3e8e04fb555373fb | rust | feature_envy | medium | struct ReportGenerator;
impl ReportGenerator {
fn generate_summary(user: &User) -> String {
let days_active = (Utc::now() - user.created_at).num_days();
let tier = if user.subscription_points > 1000 { "gold" }
else if user.subscription_points > 500 { "silver" }
... | 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. | 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. | beginner |
771a25b0509eabf4 | typescript | middle_man | medium | class ProductRepository {
constructor(private db: Database) {}
findById(id: string): Promise<Product | null> { return this.db.findById<Product>('products', id); }
findAll(): Promise<Product[]> { return this.db.findAll<Product>('products'); }
save(product: Product): Promise<Product> { ... | ProductRepository merely forwards every call to a generic Database with the 'products' table name hardcoded. There is no product-specific query logic β it is a Middle Man that hides the generic DB API behind a named faΓ§ade. | 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). | intermediate |
31d17158834026b2 | javascript | incomplete_library | medium | function formatDate(date) {
const d = new Date(date);
const year = d.getFullYear();
const month = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
const hours = String(d.getHours()).padStart(2, '0');
const minutes = String(d.getMinutes()).padStart(2, '0');
retur... | 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. | 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', ' '). | beginner |
6c64d425c27fe5a3 | typescript | refused_bequest | high | abstract class Animal {
name: string;
abstract makeSound(): string;
abstract fly(): string;
abstract swim(): string;
}
class Dog extends Animal {
makeSound() { return 'Woof'; }
fly() { throw new Error('Dogs cannot fly'); }
swim() { return 'paddling'; }
}
class Eagle extends Animal {
makeSound() { retu... | 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 β a Liskov Substitution violation. | 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. | intermediate |
5a87b4c9ef2f403d | python | comments_as_smell | low | def calc(x, y, z):
# multiply x by y
r1 = x * y
# add z to the result of multiplying x by y
r2 = r1 + z
# return the final result
return r2 | Every line is explained by a comment that restates what the code literally does. This is a sign the code is insufficiently expressive β comments are compensating for poor naming rather than explaining non-obvious intent. | 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. | beginner |
3219335a2cf7455f | go | long_method | high | func (h *Handler) ProcessWebhook(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "read error", http.StatusBadRequest)
return
}
sig := r.Header.Get("X-Signature")
expected := computeHMAC(body, h.secret)
if sig != expected {
... | 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. | 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. | intermediate |
04e7248070897606 | javascript | temporary_field | medium | class PDFExporter {
constructor(template) {
this.template = template;
this.currentPage = null; // set only during export()
this.pageBuffer = null; // set only during export()
this.fontCache = null; // set only during export()
}
async export(document) {
this.currentPage = 1;
th... | currentPage, pageBuffer, and fontCache are null before export() is called and after it returns. They exist solely to avoid passing locals between rendering helpers β indicating missing abstraction. | 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. | intermediate |
9d0ab3cdbf01c4e5 | python | inappropriate_intimacy | medium | class AnalyticsCollector:
def __init__(self, session_store):
self.store = session_store
def record_event(self, user_id, event_name):
# Reaches into session_store private implementation
session = self.store._active_sessions.get(user_id)
if session and session._raw_data.get('track... | AnalyticsCollector accesses _active_sessions, _raw_data, _event_log, and _sid β four private members across two objects. Any internal refactoring of SessionStore will silently break analytics. | 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. | intermediate |
3b4b28f2f61f7334 | java | god_object | high | @RestController
@Service
@Repository
public class UserController {
@Autowired private EntityManager em;
@Autowired private JavaMailSender mailer;
@Autowired private BCryptPasswordEncoder encoder;
@PostMapping("/register")
public ResponseEntity<?> register(@RequestBody UserDto dto) {
// Vali... | A single class annotated as @RestController, @Service, and @Repository simultaneously. It owns HTTP handling, business logic, data access, and email β all Spring layers collapsed into one class. | Follow Spring layering: UserController (HTTP only) β UserService (business logic + transactions) β UserRepository (JPA/DB). Email lives in a NotificationService. Each layer has its own @Component stereotype and dependency direction. | intermediate |
7efe9f7f0fabcead | python | temporary_field | medium | class QueryBuilder:
def __init__(self):
self._table = None
self._conditions = None
self._columns = None
self._limit = None
def build(self, table, conditions, columns, limit=None):
self._table = table
self._conditions = conditions
self._columns = columns
... | Four instance fields are assigned at the start of build() and used only within that call. They are None before and after build() β classic temporary fields that belong as local variables. | 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. | beginner |
7ddfa806f5a3de61 | typescript | large_class | high | class DashboardComponent {
// 600 lines
users: User[] = [];
orders: Order[] = [];
products: Product[] = [];
selectedTab: string = 'users';
searchQuery: string = '';
sortColumn: string = '';
sortDirection: 'asc' | 'desc' = 'asc';
currentPage: number = 1;
pageSize: number = 25;
isLoading: boolean = ... | 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. | 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). | advanced |
fc873095e83035f1 | python | message_chains | medium | def get_invoice_currency(company_id):
return (CompanyRegistry.get_instance()
.find_company(company_id)
.get_billing_account()
.get_payment_settings()
.get_preferred_currency()
.get_code()) | A six-step chain navigating CompanyRegistry β Company β BillingAccount β PaymentSettings β Currency β code. Any intermediate method returning None causes an AttributeError, and any refactoring of intermediate types ripples to this call. | 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. | intermediate |
3e75505def4ccddb | python | dead_code | low | class Config:
DEBUG = True
DATABASE_URL = 'postgresql://localhost/prod'
SECRET_KEY = 'change-me'
# Legacy config from old Redis integration β no longer used
REDIS_HOST = 'localhost'
REDIS_PORT = 6379
REDIS_PASSWORD = ''
REDIS_DB = 0
@staticmethod
def from_old_format(data):
... | 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. | 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. | beginner |
b96dc1892fe915b2 | go | data_clumps | medium | func LogRequest(method, path, clientIP string, statusCode, durationMs int) {
log.Printf("[%s] %s from %s -> %d in %dms", method, path, clientIP, statusCode, durationMs)
}
func RecordMetric(method, path, clientIP string, statusCode, durationMs int) {
metrics.Record(method, path, clientIP, statusCode, durationMs... | 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. | 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. | beginner |
0429e21b0e6ce70f | typescript | speculative_generality | medium | interface Repository<T, ID = string, Q = Record<string, unknown>> {
findById(id: ID): Promise<T | null>;
findAll(query?: Q): Promise<T[]>;
save(entity: T): Promise<T>;
delete(id: ID): Promise<void>;
count(query?: Q): Promise<number>;
exists(id: ID): Promise<boolean>;
bulkSave(entities: T[]): Promise<T[]>;... | 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. | 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. | intermediate |
Code Smell Detection
A curated synthetic dataset of 103 hand-authored code snippets labelled with software engineering code smells across 6 languages and 20 smell types, including a clean negative class (~6%). Designed for training classifiers, evaluating LLM code-review capability, and teaching refactoring principles.
Dataset Summary
| Attribute | Value |
|---|---|
| Total examples | 103 |
| Languages | Python, JavaScript, TypeScript, Go, Java, Rust |
| Smell types | 20 (+ clean negative class) |
| Splits | train (72) / val (15) / test (16) |
| License | Apache 2.0 |
Smell Types
| Smell Type | Count | Description |
|---|---|---|
long_method |
5 | Methods too long to understand at a glance |
large_class |
5 | Classes with too many responsibilities |
god_object |
5 | Objects that know/do too much |
feature_envy |
7 | Methods more interested in another class's data |
data_clumps |
6 | Groups of primitives that belong in an object |
primitive_obsession |
5 | Using primitives instead of value objects |
switch_statements |
5 | Repeated switch/if-else on a type discriminator |
speculative_generality |
6 | Unused abstraction added for hypothetical futures |
comments_as_smell |
6 | Comments that compensate for poor naming |
temporary_field |
4 | Fields only set during one method call |
message_chains |
6 | Long chains of getters/method calls |
middle_man |
5 | Classes that only delegate to another class |
inappropriate_intimacy |
4 | Classes accessing each other's private internals |
refused_bequest |
4 | Subclasses that reject inherited interface |
lazy_class |
5 | Classes that do too little to justify existence |
alternative_classes |
5 | Two classes doing the same thing with different names |
dead_code |
5 | Unreachable, deprecated, or commented-out code |
parallel_inheritance |
4 | Two class hierarchies that must change in lockstep |
incomplete_library |
5 | Re-implementing what a standard library already provides |
none |
6 | Clean negative class β well-written code with no smell |
Schema
{
"id": str, # 16-char MD5 hex
"language": str, # python | javascript | typescript | go | java | rust
"smell_type": str, # see table above; "none" for clean examples
"severity": str, # low | medium | high | none (none for clean examples)
"code_snippet": str, # the code to evaluate
"smell_explanation": str, # why this is a smell (or why it's clean)
"refactoring_suggestion": str,# how to fix it (or "No refactoring needed." for clean)
"difficulty": str # beginner | intermediate | advanced
}
Sample Records
Example 1 β feature_envy (Python, beginner)
# code_snippet:
class Report:
def __init__(self, data_source):
self.data_source = data_source
def generate(self):
records = self.data_source.records
total = sum(r.amount for r in self.data_source.records if r.status == 'paid')
overdue = [r for r in self.data_source.records if r.due_date < datetime.today() and r.status != 'paid']
avg = total / len(self.data_source.records) if self.data_source.records else 0
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 β 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().
Example 2 β message_chains (TypeScript, advanced)
// code_snippet:
function applyDiscount(context: RequestContext): number {
return context
.getSession()
.getCurrentUser()
.getSubscription()
.getPlan()
.getDiscountPolicy()
.calculateDiscount(context.getCart().getTotalAmount());
}
// smell_explanation:
// A 7-deep chain crosses five domain objects to reach a discount calculation.
// Depends on the shape of five intermediate types, 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),
// or to User.calculateDiscount(cartTotal) if discount is user-scoped.
Example 3 β none (Go, intermediate, clean)
// code_snippet:
type Money struct {
amount int64 // stored in cents
currency string // ISO 4217
}
func NewMoney(amount int64, currency string) (Money, error) {
if amount < 0 { return Money{}, fmt.Errorf("amount must be non-negative") }
if len(currency) != 3 { return Money{}, fmt.Errorf("invalid currency code") }
return Money{amount: amount, currency: currency}, nil
}
func (m Money) Add(other Money) (Money, error) {
if m.currency != other.currency {
return Money{}, fmt.Errorf("currency mismatch: %s vs %s", m.currency, other.currency)
}
return Money{amount: m.amount + other.amount, currency: m.currency}, nil
}
// smell_explanation:
// Clean value object pattern: Money is immutable, validated at construction,
// stores currency-safe integer amounts, and arithmetic is type-safe. No smell.
Usage
from datasets import load_dataset
ds = load_dataset("SalutefaceAAC/code-smell-detection")
print(ds["train"][0])
# Filter by language and severity
train_df = ds["train"].to_pandas()
high_severity = train_df[(train_df.language == "python") & (train_df.severity == "high")]
# Classify: positive examples only
positive = train_df[train_df.smell_type != "none"]
LLM Evaluation Prompt
def make_eval_prompt(snippet: str) -> str:
return f"""Analyze the following code snippet for software engineering code smells.
Identify the primary smell type (or "none" if the code is clean), its severity (low/medium/high/none),
explain why it is or isn't a smell, and suggest a refactoring if applicable.
Code:
{snippet}
Respond in JSON: {{"smell_type": "...", "severity": "...", "explanation": "...", "refactoring": "..."}}"""
Methodology
Examples were hand-authored following these principles:
- Authenticity: Each snippet resembles real-world code that would appear in a production codebase, not toy examples.
- Language idiomatic: Each language's conventions (Go interfaces, Rust newtype, Java Spring, TypeScript generics) are respected.
- Negative class: 6 clean examples (~6%) prevent classifiers from learning a trivial "always smelly" bias.
- Severity calibration:
high= structural problem affecting testability/extensibility;medium= noticeable but contained;low= minor style or maintenance debt. - Difficulty calibration:
beginner= recognisable pattern, one-line fix;intermediate= requires understanding domain/architecture;advanced= multi-class refactoring or architectural pattern.
Limitations
- 103 examples β suitable for evaluation, fine-tuning small classifiers, or few-shot prompting; not sufficient for training large models from scratch.
- Python is over-represented (29/103) relative to Rust (9/103); balance will improve in v1.5.
- Snippets are self-contained stubs; real code smells often span multiple files.
- The taxonomy follows Fowler's Refactoring (2nd ed.) and Kerievsky's Refactoring to Patterns; some newer smells (e.g., async anti-patterns, microservice coupling) are not yet covered.
- LLM-generated explanations: while hand-authored, these reflect the author's (agent's) interpretation of each smell, not a community consensus annotation.
Related Datasets
- SalutefaceAAC/synthetic-code-review-comments
- SalutefaceAAC/unit-test-edge-cases
- SalutefaceAAC/api-error-resolution-pairs
- SalutefaceAAC/structured-output-generation
Citation
@dataset{saluteface_code_smell_2026,
author = {SalutefaceAAC},
title = {Code Smell Detection},
year = {2026},
publisher = {Hugging Face},
url = {https://huggingface.co/datasets/SalutefaceAAC/code-smell-detection},
license = {Apache-2.0}
}
- Downloads last month
- 64