Skip to content

Rodrigotari1/generic-code-guidelines

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 

Repository files navigation

Coding Rules

Write code that reads like sentences. Make it generic, reusable, and self-explanatory.

Function Names

Reveal Return Type

# Good
def calculate_total_price(items): return float
def find_user_by_email(email): return User | None
def is_valid_password(password): return bool

# Bad
def process_items(items): return ??? 
def handle_user(email): return ???
def check_password(password): return ???

Be Generic, Not Vague

# Good
def parse_csv_rows(content)
def validate_email_format(email)
def sort_records_by_field(records, field)

# Bad
def process_data(data)
def handle_stuff(details)
def work_with_things(things, info)

Don't Tie to Use Cases

# Good
def calculate_percentage(part, total)
def filter_items_by_attribute(items, attr, value)
def format_currency(amount, code)

# Bad
def calculate_sales_tax_for_checkout(part, total)
def find_red_shirts_in_inventory(items, attr, value)
def format_price_for_receipt(amount, code)

Verb Conventions

Use consistent verbs to signal intent:

get_        # Fetch from external (DB, API, file)
generate_   # Create locally
calculate_  # Math operations
validate_   # Check criteria
format_     # Transform presentation
parse_      # Convert formats

# Good
def get_user_from_database(id)
def generate_random_password(length)
def calculate_compound_interest(principal, rate)

# Bad
def generate_user_from_database(id)  # Should be get_
def get_random_password(length)      # Should be generate_

Variable Names

Reveal Type and Content

# Good
user_list = [User(), User()]
user_count = 42
is_authenticated = True
error_message = "Invalid format"
price_in_cents = 2599

# Bad
data = [User(), User()]
num = 42
flag = True
msg = "Invalid format"
price = 2599

No Comments Needed

# Good
maximum_retry_attempts = 3
database_connection_timeout_seconds = 30

# Bad
max_retries = 3  # Maximum retry attempts
timeout = 30     # DB timeout in seconds

Naming Patterns

Consistent Ordering

Group related items with shared prefixes:

# Good
user_create_account()
user_authenticate_login()
user_update_profile()
user_delete_account()

# Bad
create_user_account()
authenticate_user_login()
update_user_profile()
delete_user_account()

Meaningful Structures

# Good
class CustomerOrder:
    customer_id: str
    items: list
    shipping_address: str

user_preferences = {
    'theme': 'dark',
    'notifications': True
}

# Bad
class DataContainer:
    id: str
    stuff: list
    location: str

settings = {
    'theme': 'dark',
    'notifications': True
}

Design Principles

Single Responsibility

If you can't name it clearly, it does too much:

# Bad
def process_order_and_update_inventory_and_send_email(order)

# Good
def validate_order_data(order)
def update_inventory_quantities(items)
def send_order_confirmation(email, details)

Warning Signs

Function needs refactoring if:

  • Name contains "and" or multiple verbs
  • Can't describe in one sentence
  • Name over 4 words
  • Needs comments to explain

Abstract Complexity

Hide implementation details:

# Good
def send_welcome_email(email, name)
def process_payment(amount, method)

# Bad
def send_welcome_email_via_sendgrid_with_analytics(email, name)
def process_credit_card_through_stripe_api(amount, card)

Design for Reuse

Write for contexts you haven't thought of:

# Good
def calculate_distance_between_points(p1, p2)
def apply_discount_to_amount(amount, percent)
def group_items_by_attribute(items, attr)

# Bad
def calculate_shipping_distance_for_ecommerce(warehouse, customer)
def apply_black_friday_discount_to_cart(cart_total)

Quick Checklist

Before committing:

  • Function names reveal return types
  • No vague words (data, stuff, info, details)
  • Not tied to specific use cases
  • Consistent verb conventions
  • Variables reveal type and content
  • No explanatory comments needed
  • Consistent prefix ordering
  • Single responsibility per function
  • Implementation details hidden

Examples

Before

def process_data(data):
    # Calculate tax for checkout
    result = data * 0.08
    return result

def handle_stuff(things, info):
    # Filter items
    return [x for x in things if getattr(x, info) == 'red']

max_tries = 3  # Maximum retries

After

def calculate_percentage(part, total):
    return (part / total) * 100

def filter_items_by_attribute(items, attribute_name, target_value):
    return [item for item in items 
            if getattr(item, attribute_name) == target_value]

maximum_retry_attempts = 3

Write code that explains itself. If you need comments, improve the names.

About

Generic code guidelines

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published