SalutefaceAAC commited on
Commit
f52030f
·
verified ·
1 Parent(s): b6a9d74

Add test JSONL split

Browse files
Files changed (1) hide show
  1. data/test.jsonl +16 -0
data/test.jsonl ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"id": "9365cd0d376e2ed8", "language": "python", "smell_type": "data_clumps", "severity": "medium", "code_snippet": "def send_payment(card_number, card_expiry, card_cvv, card_holder, amount, currency):\n validate_card(card_number, card_expiry, card_cvv)\n charge = gateway.charge(card_number, card_expiry, card_cvv, card_holder, amount, currency)\n return charge\n\ndef refund_payment(card_number, card_expiry, card_cvv, card_holder, charge_id, amount):\n validate_card(card_number, card_expiry, card_cvv)\n return gateway.refund(card_number, card_expiry, card_cvv, charge_id, amount)", "smell_explanation": "The four card fields (number, expiry, cvv, holder) always travel together across every function signature. Data clumps like this indicate a missing abstraction and increase the risk of parameter ordering mistakes.", "refactoring_suggestion": "Create a CreditCard dataclass with number, expiry, cvv, holder fields. Pass a single CreditCard object; validation becomes card.validate(). Callers gain readability and type safety.", "difficulty": "beginner"}
2
+ {"id": "c41bc10e8a7f937a", "language": "go", "smell_type": "comments_as_smell", "severity": "low", "code_snippet": "// GetUserByID returns the user with the given ID\nfunc GetUserByID(id int) (*User, error) {\n // Query the database for the user\n row := db.QueryRow(\"SELECT id, name, email FROM users WHERE id = ?\", id)\n // Create a new user struct\n user := &User{}\n // Scan the row into the user struct\n err := row.Scan(&user.ID, &user.Name, &user.Email)\n // Return the user or the error\n return user, err\n}", "smell_explanation": "The function doc comment is redundant with the function name; inline comments restate each line's obvious action. In Go, doc comments should describe behaviour, edge cases, or guarantees \u2014 not narrate the implementation.", "refactoring_suggestion": "Keep only a doc comment if it adds non-obvious context: // GetUserByID returns ErrNoRows if no user exists. Remove all inline comments. Code structure is already clear.", "difficulty": "beginner"}
3
+ {"id": "0321e53c93d98127", "language": "typescript", "smell_type": "message_chains", "severity": "high", "code_snippet": "function applyDiscount(context: RequestContext): number {\n return context\n .getSession()\n .getCurrentUser()\n .getSubscription()\n .getPlan()\n .getDiscountPolicy()\n .calculateDiscount(context.getCart().getTotalAmount());\n}", "smell_explanation": "A 7-deep chain crosses five domain objects to reach a discount calculation. The function depends on the shape of five intermediate types, is impossible to unit-test without a full context graph, and violates the Law of Demeter severely.", "refactoring_suggestion": "Move calculateDiscount to a DiscountService that accepts (userId, planId, cartTotal) \u2014 or to User.calculateDiscount(cartTotal) if discount is user-scoped. The function should ask for the result, not traverse the object graph to compute it.", "difficulty": "advanced"}
4
+ {"id": "02f7aaf1b083f735", "language": "javascript", "smell_type": "switch_statements", "severity": "medium", "code_snippet": "function getDiscount(userType, total) {\n let discount = 0;\n switch (userType) {\n case 'gold': discount = total * 0.20; break;\n case 'silver': discount = total * 0.10; break;\n case 'bronze': discount = total * 0.05; break;\n case 'vip': discount = total * 0.30; break;\n default: discount = 0;\n }\n return discount;\n}", "smell_explanation": "A switch on userType means every new tier requires modifying this function. The switch is duplicated wherever discount logic appears (invoicing, cart, reporting), making additions risky and forgetful.", "refactoring_suggestion": "Use a data-driven lookup: const DISCOUNT_RATES = { gold: 0.20, silver: 0.10, bronze: 0.05, vip: 0.30 }; return total * (DISCOUNT_RATES[userType] ?? 0). Or apply the Strategy/Policy pattern if tier logic grows more complex.", "difficulty": "beginner"}
5
+ {"id": "f99958025f1aa1e0", "language": "python", "smell_type": "incomplete_library", "severity": "medium", "code_snippet": "import re\n\ndef is_valid_email(email: str) -> bool:\n pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$'\n return bool(re.match(pattern, email))\n\ndef is_valid_url(url: str) -> bool:\n pattern = r'^https?://[^\\s/$.?#].[^\\s]*$'\n return bool(re.match(pattern, url))\n\ndef is_valid_phone(phone: str) -> bool:\n pattern = r'^\\+?[1-9]\\d{7,14}$'\n return bool(re.match(pattern, phone))", "smell_explanation": "Home-rolled regex validators for email, URL, and phone. Email regex is known to be subtly wrong for edge cases (IDN, new TLDs). The `email-validator` and `validators` libraries handle these correctly with RFC compliance.", "refactoring_suggestion": "Use email-validator (pip install email-validator) for email: from email_validator import validate_email. Use urllib.parse.urlparse for URL structure checks. Use phonenumbers library for phone validation. Don't reinvent established validators.", "difficulty": "intermediate"}
6
+ {"id": "b32e64adabb64341", "language": "python", "smell_type": "data_clumps", "severity": "high", "code_snippet": "def create_employee(first_name, last_name, email, phone,\n street, city, state, postal_code, country,\n department, title, start_date, salary, currency):\n ...\n\ndef update_employee(employee_id, first_name, last_name, email, phone,\n street, city, state, postal_code, country,\n department, title, salary, currency):\n ...", "smell_explanation": "Fourteen primitive parameters, with three obvious clumps: name (first+last), address (street+city+state+postal+country), and compensation (salary+currency). Every signature change ripples to all callers.", "refactoring_suggestion": "Introduce PersonName(first, last), Address(street, city, state, postal_code, country), and Money(amount, currency) value objects. create_employee(name: PersonName, contact: ContactInfo, address: Address, role: RoleInfo, comp: Money).", "difficulty": "intermediate"}
7
+ {"id": "30c8fcfd41b6972a", "language": "javascript", "smell_type": "primitive_obsession", "severity": "high", "code_snippet": "function createEvent(title, startYear, startMonth, startDay, startHour, startMinute,\n endYear, endMonth, endDay, endHour, endMinute, locationLat, locationLng) {\n const start = new Date(startYear, startMonth - 1, startDay, startHour, startMinute);\n const end = new Date(endYear, endMonth - 1, endDay, endHour, endMinute);\n if (end <= start) throw new Error('End must be after start');\n return { title, start, end, location: { lat: locationLat, lng: locationLng } };\n}", "smell_explanation": "Thirteen primitive parameters for what is conceptually two datetimes and one coordinate pair. The long signature is error-prone (month-day-hour ordering), untestable in isolation, and impossible to read at call sites.", "refactoring_suggestion": "Accept { start: Date, end: Date, location: { lat, lng } }. Callers construct Date objects themselves, which is standard JS. Destructured options objects are self-documenting and extensible.", "difficulty": "beginner"}
8
+ {"id": "5f92a45b153703de", "language": "go", "smell_type": "dead_code", "severity": "medium", "code_snippet": "package config\n\n// loadFromFile reads config from a JSON file.\n// Deprecated: use LoadFromEnv instead. Kept for local development.\nfunc loadFromFile(path string) (*Config, error) {\n // 40 lines of JSON parsing...\n}\n\n// debugDumpConfig prints all config values.\n// Remove before release - left in for debugging.\nfunc debugDumpConfig(c *Config) {\n fmt.Printf(\"%+v\n\", c)\n}", "smell_explanation": "A deprecated file-based loader and a debug-dump function marked 'remove before release' are still in production code. The deprecation comment implies loadFromFile is still used; the debug comment implies debugDumpConfig was already meant to be deleted.", "refactoring_suggestion": "Delete both functions. If loadFromFile is still needed in development, gate it with a build tag (//go:build dev). Debug dump utility can be replaced by log.Printf or a test helper. Remove 'Deprecated:' comments that describe code rather than guide users.", "difficulty": "beginner"}
9
+ {"id": "c9abcfe40ffe3b49", "language": "javascript", "smell_type": "middle_man", "severity": "low", "code_snippet": "class UserService {\n constructor(userRepository) {\n this.repo = userRepository;\n }\n findById(id) { return this.repo.findById(id); }\n findByEmail(email) { return this.repo.findByEmail(email); }\n save(user) { return this.repo.save(user); }\n delete(id) { return this.repo.delete(id); }\n findAll() { return this.repo.findAll(); }\n}", "smell_explanation": "UserService adds no logic \u2014 every method is a one-liner delegation to userRepository. It is a pure Middle Man providing zero value while adding an extra layer to navigate and maintain.", "refactoring_suggestion": "Delete UserService and inject UserRepository directly. If domain logic is ever needed (e.g., password hashing, permission checks), add a real service at that point. Don't create layers speculatively.", "difficulty": "beginner"}
10
+ {"id": "3099f0bf11afc067", "language": "go", "smell_type": "large_class", "severity": "high", "code_snippet": "type UserService struct {\n db *sql.DB\n cache *redis.Client\n mailer *Mailer\n sms *SMSClient\n s3 *s3.Client\n stripe *stripe.Client\n}\n\n// 50+ methods including:\nfunc (s *UserService) Register(...) {}\nfunc (s *UserService) Login(...) {}\nfunc (s *UserService) ForgotPassword(...) {}\nfunc (s *UserService) UpdateProfile(...) {}\nfunc (s *UserService) UploadAvatar(...) {}\nfunc (s *UserService) GetFeed(...) {}\nfunc (s *UserService) Follow(...) {}\nfunc (s *UserService) Unsubscribe(...) {}\nfunc (s *UserService) ExportGDPR(...) {}\nfunc (s *UserService) DeleteAccount(...) {}\nfunc (s *UserService) ChargeSubscription(...) {}\nfunc (s *UserService) GenerateInvoice(...) {}", "smell_explanation": "UserService has six infrastructure dependencies and 50+ methods covering auth, profiles, media, social, billing, and compliance. It will require changes for every unrelated feature and be a merge-conflict magnet.", "refactoring_suggestion": "Decompose into AuthService, ProfileService, MediaService, SocialService, BillingService, ComplianceService. Each takes only its relevant dependencies. Wire them in the service layer via composition or interfaces.", "difficulty": "intermediate"}
11
+ {"id": "f64c3e6d07ca1183", "language": "java", "smell_type": "switch_statements", "severity": "high", "code_snippet": "public double calculateShipping(String carrierCode, double weight, String destination) {\n switch (carrierCode) {\n case \"FEDEX\":\n if (destination.equals(\"INTERNATIONAL\")) return weight * 8.5 + 15.0;\n return weight * 3.2 + 5.0;\n case \"UPS\":\n if (destination.equals(\"INTERNATIONAL\")) return weight * 9.0 + 12.0;\n return weight * 2.9 + 4.5;\n case \"USPS\":\n return weight * 1.8 + 3.0;\n case \"DHL\":\n return weight * 10.5 + 20.0;\n default:\n throw new IllegalArgumentException(\"Unknown carrier: \" + carrierCode);\n }\n}", "smell_explanation": "A switch on carrier codes with nested conditionals for destination. Adding a new carrier or changing a rate formula requires modifying this method, violating Open/Closed Principle. The logic will also be duplicated in related methods.", "refactoring_suggestion": "Use a strategy pattern: interface ShippingCarrier { double calculateRate(double weight, String destination); } with FedExCarrier, UpsCarrier, etc. A CarrierRegistry maps codes to implementations. calculateShipping delegates to the registry.", "difficulty": "intermediate"}
12
+ {"id": "eb2a00655e929699", "language": "java", "smell_type": "large_class", "severity": "high", "code_snippet": "@Service\npublic class ProductService {\n // 800 lines, 40+ methods\n public Product createProduct(...) {}\n public Product updateProduct(...) {}\n public void deleteProduct(...) {}\n public List<Product> search(...) {}\n public void updateInventory(...) {}\n public void reserveStock(...) {}\n public void releaseStock(...) {}\n public void triggerReorder(...) {}\n public BigDecimal calculatePrice(...) {}\n public BigDecimal applyBulkDiscount(...) {}\n public void attachImage(...) {}\n public void removeImage(...) {}\n public ProductReview addReview(...) {}\n public void flagReview(...) {}\n public List<Product> getRecommendations(...) {}\n public void exportCatalog(...) {}\n}", "smell_explanation": "An 800-line service class covering CRUD, inventory management, pricing, media, reviews, recommendations, and exports. Each of these is a separate bounded context; a single Spring service violates SRP and makes bounded-context testing impossible.", "refactoring_suggestion": "Split: ProductCatalogService (CRUD + search), InventoryService (stock management + reorder), PricingService (price + discounts), MediaService (images), ReviewService (reviews + flagging), RecommendationService. Each injects only its relevant repositories.", "difficulty": "advanced"}
13
+ {"id": "0a6c0c70d8b72985", "language": "python", "smell_type": "refused_bequest", "severity": "high", "code_snippet": "class Shape:\n def area(self): raise NotImplementedError\n def perimeter(self): raise NotImplementedError\n def volume(self): raise NotImplementedError # 3D only\n def surface_area(self): raise NotImplementedError # 3D only\n\nclass Circle(Shape):\n def __init__(self, r): self.r = r\n def area(self): return 3.14159 * self.r ** 2\n def perimeter(self): return 2 * 3.14159 * self.r\n def volume(self): raise TypeError(\"Circle has no volume\")\n def surface_area(self): raise TypeError(\"Circle has no surface area\")\n\nclass Sphere(Shape):\n def __init__(self, r): self.r = r\n def area(self): raise TypeError(\"Sphere area is ambiguous \u2014 use surface_area()\")\n def perimeter(self): raise TypeError(\"Sphere has no perimeter\")\n def volume(self): return (4/3) * 3.14159 * self.r ** 3\n def surface_area(self): return 4 * 3.14159 * self.r ** 2", "smell_explanation": "Shape defines both 2D and 3D interfaces. Circle refuses volume() and surface_area(); Sphere refuses perimeter() and area(). Both subclasses throw exceptions for inherited methods \u2014 a textbook Refused Bequest + LSP violation.", "refactoring_suggestion": "Separate: class Shape2D(ABC): area(), perimeter(); class Shape3D(ABC): volume(), surface_area(). Circle(Shape2D); Sphere(Shape3D). No subclass inherits methods it cannot implement.", "difficulty": "intermediate"}
14
+ {"id": "ec61164a1f725772", "language": "python", "smell_type": "primitive_obsession", "severity": "medium", "code_snippet": "def schedule_meeting(user_id, start_hour, start_minute, duration_minutes, room_name, building, floor):\n if start_hour < 0 or start_hour > 23:\n raise ValueError(\"Invalid hour\")\n if start_minute < 0 or start_minute > 59:\n raise ValueError(\"Invalid minute\")\n if duration_minutes < 15:\n raise ValueError(\"Meeting too short\")\n end_minute = (start_minute + duration_minutes) % 60\n end_hour = start_hour + (start_minute + duration_minutes) // 60\n room_code = f\"{building}-{floor}-{room_name}\"\n ...", "smell_explanation": "Time is represented as two separate integers (hour, minute), location as three separate strings. Validation and arithmetic are scattered across callers. Primitive types carry no domain semantics.", "refactoring_suggestion": "Introduce TimeSlot(start: datetime, duration: timedelta) and Room(building, floor, name) value objects. Validation lives inside the constructors; callers pass meaningful objects rather than raw primitives.", "difficulty": "beginner"}
15
+ {"id": "5947d2cfac3e2cb3", "language": "javascript", "smell_type": "god_object", "severity": "high", "code_snippet": "class App {\n constructor() {\n this.router = express();\n this.db = null;\n this.cache = null;\n this.mailer = null;\n this.jobs = [];\n this.sockets = [];\n this.metrics = {};\n }\n connectDB() { ... }\n connectRedis() { ... }\n registerRoutes() { ... }\n registerMiddleware() { ... }\n startWorkers() { ... }\n scheduleJobs() { ... }\n initWebSockets() { ... }\n sendEmail() { ... }\n trackMetric() { ... }\n shutdown() { ... }\n restart() { ... }\n}", "smell_explanation": "App owns the database, cache, mailer, job queue, WebSocket connections, metrics, routing, and lifecycle. It is a God Object: any change anywhere requires modifying this class, and tests require spinning up the entire system.", "refactoring_suggestion": "Follow composition root pattern: create DatabaseModule, CacheModule, MailModule, WorkerModule, etc. App's constructor wires them together but delegates all logic. Each module is independently configurable and testable.", "difficulty": "intermediate"}
16
+ {"id": "901aa2a9cc554047", "language": "python", "smell_type": "switch_statements", "severity": "medium", "code_snippet": "def format_value(value, fmt_type):\n if fmt_type == 'currency':\n return f'${value:,.2f}'\n elif fmt_type == 'percentage':\n return f'{value:.1f}%'\n elif fmt_type == 'integer':\n return f'{int(value):,}'\n elif fmt_type == 'decimal':\n return f'{value:.4f}'\n elif fmt_type == 'scientific':\n return f'{value:.2e}'\n else:\n return str(value)", "smell_explanation": "A chain of elif branches on fmt_type that will grow every time a new format is added. The same pattern is duplicated in display, export, and reporting code with slight variations, causing inconsistency.", "refactoring_suggestion": "Use a dispatch dict: FORMATTERS = {'currency': lambda v: f'${v:,.2f}', 'percentage': lambda v: f'{v:.1f}%', ...}. format_value(value, fmt_type) returns FORMATTERS.get(fmt_type, str)(value). New formats are data, not code branches.", "difficulty": "beginner"}