--- license: apache-2.0 language: - en tags: - code - software-engineering - synthetic - code-quality - refactoring - static-analysis task_categories: - text-classification - text-generation pretty_name: Code Smell Detection size_categories: - n<1K --- # 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 ```python { "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) ```python # 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) ```typescript // 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) ```go // 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 ```python 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 ```python 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](https://huggingface.co/datasets/SalutefaceAAC/synthetic-code-review-comments) - [SalutefaceAAC/unit-test-edge-cases](https://huggingface.co/datasets/SalutefaceAAC/unit-test-edge-cases) - [SalutefaceAAC/api-error-resolution-pairs](https://huggingface.co/datasets/SalutefaceAAC/api-error-resolution-pairs) - [SalutefaceAAC/structured-output-generation](https://huggingface.co/datasets/SalutefaceAAC/structured-output-generation) ## Citation ```bibtex @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} } ```