295 lines
9.8 KiB
Python
295 lines
9.8 KiB
Python
#!/usr/bin/env python3
|
|
|
|
"""
|
|
Sample Code for Roasting - Deliberately Imperfect Code
|
|
This file contains examples of code issues that the Roast Bot will identify
|
|
"""
|
|
|
|
import os
|
|
import sys
|
|
import random
|
|
import time
|
|
import json
|
|
import requests
|
|
from typing import Dict, List, Optional, Any
|
|
|
|
# Global variables (bad practice)
|
|
GLOBAL_COUNTER = 0
|
|
DATABASE_URL = "localhost"
|
|
API_KEY = "secret_key_123"
|
|
|
|
def very_long_function_with_many_parameters_and_complex_logic(
|
|
param1, param2, param3, param4, param5, param6, param7, param8, param9, param10
|
|
):
|
|
"""
|
|
This function is way too long and has too many parameters
|
|
It also has very deep nesting and complex logic that's hard to follow
|
|
"""
|
|
global GLOBAL_COUNTER
|
|
|
|
# Deep nesting level 1
|
|
if param1 == "test":
|
|
# Deep nesting level 2
|
|
for i in range(100):
|
|
# Deep nesting level 3
|
|
if i % 2 == 0:
|
|
# Deep nesting level 4
|
|
for j in range(50):
|
|
# Deep nesting level 5
|
|
if j % 3 == 0:
|
|
# Deep nesting level 6
|
|
while GLOBAL_COUNTER < 1000:
|
|
# Deep nesting level 7
|
|
if random.random() > 0.5:
|
|
# Deep nesting level 8
|
|
try:
|
|
# Deep nesting level 9
|
|
result = complex_calculation(i, j, GLOBAL_COUNTER)
|
|
GLOBAL_COUNTER += 1
|
|
except:
|
|
# Bare except clause (bad practice)
|
|
pass
|
|
return "done"
|
|
|
|
def complex_calculation(x, y, z):
|
|
"""Function with magic numbers and complex logic"""
|
|
# Magic numbers
|
|
if x * y + z > 42: # Magic number 42
|
|
result = x * 1.5 + y * 2.7 - z * 0.3 # More magic numbers
|
|
else:
|
|
result = (x + y + z) / 3.14 # Magic number 3.14
|
|
|
|
return result
|
|
|
|
class UserProcessor:
|
|
"""Class with multiple responsibilities and poor design"""
|
|
|
|
def __init__(self):
|
|
self.users = []
|
|
self.database_connection = None
|
|
self.cache = {}
|
|
self.logger = None
|
|
self.config = {}
|
|
self.metrics = {}
|
|
self.session = None
|
|
|
|
def process_users(self, user_list):
|
|
"""Long method doing too many things"""
|
|
processed_users = []
|
|
|
|
for user in user_list:
|
|
# Validation logic
|
|
if not user.get('name'):
|
|
continue
|
|
|
|
if not user.get('email'):
|
|
continue
|
|
|
|
if not user.get('age'):
|
|
continue
|
|
|
|
# Data transformation
|
|
processed_user = {
|
|
'name': user['name'].upper(),
|
|
'email': user['email'].lower(),
|
|
'age': int(user['age']),
|
|
'status': 'active',
|
|
'created_at': time.time(),
|
|
'metadata': {
|
|
'source': 'api',
|
|
'version': '1.0',
|
|
'processed_by': 'UserProcessor'
|
|
}
|
|
}
|
|
|
|
# Database operations
|
|
try:
|
|
self.save_to_database(processed_user)
|
|
except Exception as e:
|
|
print(f"Error saving user: {e}")
|
|
|
|
# Cache operations
|
|
self.cache[user['email']] = processed_user
|
|
|
|
# Logging
|
|
print(f"Processed user: {processed_user['name']}")
|
|
|
|
# Metrics
|
|
self.metrics['users_processed'] = self.metrics.get('users_processed', 0) + 1
|
|
|
|
processed_users.append(processed_user)
|
|
|
|
# Additional processing
|
|
self.generate_report(processed_users)
|
|
self.send_notifications(processed_users)
|
|
self.cleanup_old_data()
|
|
|
|
return processed_users
|
|
|
|
def save_to_database(self, user):
|
|
"""Database operation with no error handling specifics"""
|
|
# This would normally connect to a database
|
|
query = f"INSERT INTO users (name, email, age) VALUES ('{user['name']}', '{user['email']}', {user['age']})"
|
|
print(f"Executing query: {query}")
|
|
|
|
def generate_report(self, users):
|
|
"""Generate a simple report"""
|
|
report = {
|
|
'total_users': len(users),
|
|
'average_age': sum(u['age'] for u in users) / len(users) if users else 0,
|
|
'generated_at': time.time()
|
|
}
|
|
print(f"Report: {report}")
|
|
|
|
def send_notifications(self, users):
|
|
"""Send notifications to users"""
|
|
for user in users:
|
|
message = f"Welcome {user['name']}!"
|
|
print(f"Sending notification: {message}")
|
|
|
|
def cleanup_old_data(self):
|
|
"""Cleanup old data from database"""
|
|
print("Cleaning up old data...")
|
|
|
|
def function_with_multiple_returns(value):
|
|
"""Function with multiple return points"""
|
|
if value < 0:
|
|
return "negative"
|
|
elif value == 0:
|
|
return "zero"
|
|
elif value < 10:
|
|
return "small"
|
|
elif value < 100:
|
|
return "medium"
|
|
else:
|
|
return "large"
|
|
|
|
def function_with_long_line():
|
|
"""Function with excessively long line"""
|
|
very_long_string = "This is a very long string that exceeds the typical line length limit and should be broken up into multiple lines for better readability and maintainability in the codebase but it's all on one line which is bad practice"
|
|
return very_long_string
|
|
|
|
# TODO: Fix this function later
|
|
def deprecated_function():
|
|
"""This function is deprecated but still in use"""
|
|
print("This function is deprecated and should be removed")
|
|
|
|
# FIXME: This function has a bug
|
|
def buggy_function():
|
|
"""Function with known bug"""
|
|
result = []
|
|
for i in range(10):
|
|
result.append(i)
|
|
# Bug: This will cause infinite loop
|
|
if i == 5:
|
|
i = 0 # This resets the loop counter
|
|
return result
|
|
|
|
# HACK: Quick fix for production
|
|
def quick_fix():
|
|
"""Temporary fix that should be refactored"""
|
|
# This is a quick hack to get things working
|
|
data = {"temp": True, "fix": "urgent"}
|
|
return json.dumps(data)
|
|
|
|
def regex_complexity():
|
|
"""Function with overly complex regular expression"""
|
|
import re
|
|
|
|
# Complex regex that's hard to understand
|
|
complex_pattern = r'^((?P<protocol>https?|ftp):\/\/)?((?P<user>[^:@]+)(?::(?P<password>[^@]+))?@)?(?P<host>[^\/?:]+)(?::(?P<port>\d+))?(?P<path>\/[^?]*)?(?:\?(?P<query>[^#]*))?(?:#(?P<fragment>.*))?$'
|
|
|
|
text = "https://user:pass@example.com:8080/path?query=value#fragment"
|
|
match = re.match(complex_pattern, text)
|
|
|
|
if match:
|
|
return match.groupdict()
|
|
return None
|
|
|
|
def duplicate_code_example():
|
|
"""Example of code duplication"""
|
|
# Processing user data
|
|
users = [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}]
|
|
|
|
# Duplicate processing logic
|
|
for user in users:
|
|
if user['age'] >= 18:
|
|
print(f"{user['name']} is an adult")
|
|
user['status'] = 'adult'
|
|
else:
|
|
print(f"{user['name']} is a minor")
|
|
user['status'] = 'minor'
|
|
|
|
# Duplicate logic with slight variation
|
|
for user in users:
|
|
if user['age'] >= 21:
|
|
print(f"{user['name']} can drink alcohol")
|
|
user['can_drink'] = True
|
|
else:
|
|
print(f"{user['name']} cannot drink alcohol")
|
|
user['can_drink'] = False
|
|
|
|
def unused_variables():
|
|
"""Function with unused variables"""
|
|
active = True
|
|
debug_mode = False
|
|
version = "1.0.0"
|
|
timestamp = time.time()
|
|
|
|
# Many variables defined but never used
|
|
config = {"setting1": True, "setting2": False}
|
|
metadata = {"created": timestamp, "version": version}
|
|
temp_data = []
|
|
|
|
# Only one variable is actually used
|
|
print(f"Application version: {version}")
|
|
|
|
def deep_function_nesting():
|
|
"""Function with extremely deep nesting"""
|
|
data = {"users": []}
|
|
|
|
# Level 1
|
|
if data.get("users"):
|
|
# Level 2
|
|
for user in data["users"]:
|
|
# Level 3
|
|
if user.get("active"):
|
|
# Level 4
|
|
if user.get("profile"):
|
|
# Level 5
|
|
if user["profile"].get("settings"):
|
|
# Level 6
|
|
if user["profile"]["settings"].get("notifications"):
|
|
# Level 7
|
|
if user["profile"]["settings"]["notifications"].get("email"):
|
|
# Level 8
|
|
if user["profile"]["settings"]["notifications"]["email"].get("enabled"):
|
|
# Level 9
|
|
if user["profile"]["settings"]["notifications"]["email"]["enabled"] == True:
|
|
# Level 10
|
|
print("Email notifications enabled")
|
|
# Level 11
|
|
for preference in user["profile"]["settings"]["notifications"]["email"].get("preferences", []):
|
|
# Level 12
|
|
if preference.get("active"):
|
|
# Level 13
|
|
print(f"Processing preference: {preference['name']}")
|
|
|
|
if __name__ == "__main__":
|
|
# Run some of the problematic functions
|
|
print("Running sample code with various issues...")
|
|
|
|
# This will demonstrate the code issues
|
|
very_long_function_with_many_parameters_and_complex_logic(
|
|
"test", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
|
|
)
|
|
|
|
processor = UserProcessor()
|
|
sample_users = [
|
|
{"name": "Alice", "email": "alice@example.com", "age": 25},
|
|
{"name": "Bob", "email": "bob@example.com", "age": 30}
|
|
]
|
|
processor.process_users(sample_users)
|
|
|
|
print("Sample code execution complete!")
|
|
print("This code contains many issues that the Roast Bot will identify!") |