File size: 8,910 Bytes
c591700
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
---
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}
}
```