Back

[Python] Professional Naming Conventions & Folder Structure

1. General Naming Rules

  • Use CamelCase for class names (AuthService ✅, authservice ❌).
  • Use snake_case for file and function names (auth_service.py ✅, AuthService.py ❌).
  • Prefix interfaces with I (IUserRepository ✅, UserRepositoryInterface ❌).
  • Suffix classes properly based on their responsibility (AuthService, UserRepository).
  • Constants should be in UPPER_CASE (MAX_RETRIES = 3).
  • Avoid abbreviations (calculate_total_price() ✅, calcTotalPrc() ❌).
  • Keep names meaningful (fetch_user_data() ✅, getData() ❌).

2. Professional Naming Conventions & Folder Structure

📜 Most Used and Important Categories

✅ Configuration (Config)

  • Description: Stores application-level configurations, environment variables, and settings.
  • Suffix/Prefix: Config
  • Example Class: AppConfig
  • Example File: app_config.py

Code Example:

class AppConfig:
    DATABASE_URL = "postgresql://user:password@localhost/db_name"
    SECRET_KEY = "mysecretkey"
    DEBUG = True

✅ Repository (Repository)

  • Description: Handles all database interactions such as CRUD operations.
  • Suffix/Prefix: Repository
  • Example Class: UserRepository
  • Example File: user_repository.py

Code Example:

class UserRepository:
    def create_user(self, user):
        pass

    def get_user_by_id(self, user_id):
        pass

✅ Service (Service)

  • Description: Contains business logic and core functionality of the application.
  • Suffix/Prefix: Service
  • Example Class: AuthService
  • Example File: auth_service.py

Code Example:

class AuthService:
    def login(self, email, password):
        pass

    def register(self, user):
        pass

✅ Controller (Controller)

  • Description: Handles incoming HTTP requests and responses (API Endpoints).
  • Suffix/Prefix: Controller
  • Example Class: AuthController
  • Example File: auth_controller.py

Code Example:

from fastapi import APIRouter

router = APIRouter()

@router.post("/login")
def login():
    pass

@router.post("/register")
def register():
    pass

✅ Middleware (Middleware)

  • Description: Handles request interception like authentication, logging, or custom headers.
  • Suffix/Prefix: Middleware
  • Example Class: AuthMiddleware
  • Example File: auth_middleware.py

Code Example:

from fastapi import Request

class AuthMiddleware:
    async def __call__(self, request: Request, call_next):
        response = await call_next(request)
        return response

✅ Validator (Validator)

  • Description: Validates incoming data or request payloads.
  • Suffix/Prefix: Validator
  • Example Class: UserValidator
  • Example File: user_validator.py

Code Example:

class UserValidator:
    def validate_email(self, email):
        pass

    def validate_password(self, password):
        pass

📜 Rarely Used Categories

✅ Processor (Processor)

  • Description: Handles background tasks, processing, and complex operations.
  • Suffix/Prefix: Processor
  • Example Class: OTPProcessor
  • Example File: otp_processor.py

Code Example:

class OTPProcessor:
    def generate_otp(self, phone_number):
        pass

    def verify_otp(self, phone_number, otp):
        pass

✅ Adapter (Adapter)

  • Description: Connects two different systems or APIs together.
  • Suffix/Prefix: Adapter
  • Example Class: EmailAdapter
  • Example File: email_adapter.py

Code Example:

class EmailAdapter:
    def send_email(self, to_email, subject, message):
        pass

✅ Factory (Factory)

  • Description: Handles object creation and complex object construction.
  • Suffix/Prefix: Factory
  • Example Class: UserFactory
  • Example File: user_factory.py

Code Example:

class UserFactory:
    def create_user(self, name, email):
        return { "name": name, "email": email }

✅ Observer (Observer)

  • Description: Listens to events and triggers actions (Event-driven programming).
  • Suffix/Prefix: Observer
  • Example Class: EmailObserver
  • Example File: email_observer.py

Code Example:

class EmailObserver:
    def send_email_notification(self, user):
        pass

✅ Proxy (Proxy)

  • Description: Acts as an intermediary to control access or add functionality.
  • Suffix/Prefix: Proxy
  • Example Class: UserProxy
  • Example File: user_proxy.py

Code Example:

class UserProxy:
    def get_user(self, user_id):
        pass

3. Professional Folder Structure

project_root/
│── src/
│   ├── controllers/        # Handles HTTP requests
│   ├── services/           # Business logic layer
│   ├── repositories/       # Database interaction layer
│   ├── models/             # Data models and ORM schemas
│   ├── middlewares/        # Request interception & processing
│   ├── utils/              # Helper functions and utilities
│── config/                 # Configuration files and environment settings
│── tests/                  # Unit and integration tests
│── docs/                   # Project documentation
│── logs/                   # Log files
│── scripts/                # Deployment and automation scripts
│── requirements.txt        # Dependencies
│── README.md               # Project overview and usage instructions
│── .env                    # Environment variables

4. Function & Variable Naming Rules

Function Naming:

  • Use snake_case for function names: get_user_by_id()
  • Start function names with verbs that describe the action:
  • fetch_users()
  • calculate_discount()
  • validate_email()
  • Private/internal functions should start with an underscore: _hash_password()
  • Use clear and descriptive names:
  • send_verification_email()
  • get_user_profile_data()

Variable Naming:

  • Use snake_case for variables:
  • user_name = "Jay Patel"
  • total_amount = 500
  • Use descriptive names, avoid single-letter variables (except for loop counters):
  • u = get_user() ❌ (not clear)
  • user = get_user()
  • Boolean variables should start with is_, has_, or can_:
  • is_active = True
  • has_permission = False
  • Use plural names for collections:
  • user_list = []
  • products = {}

This ensures clean and scalable project structures! 🚀

[JavaScript] Professional Naming Conventions & Folder Structure

1. General Naming Rules

  • Use PascalCase for class names (AuthService ✅, authservice ❌).
  • Use camelCase for function and variable names (authService.js ✅, AuthService.js ❌).
  • Prefix interfaces with I (IUserRepository ✅, UserRepositoryInterface ❌).
  • Suffix classes properly based on their responsibility (AuthService, UserRepository).
  • Constants should be in UPPER_CASE (MAX_RETRIES = 3).
  • Avoid abbreviations (calculateTotalPrice() ✅, calcTotalPrc() ❌).
  • Keep names meaningful (fetchUserData() ✅, getData() ❌).

2. Professional Naming Conventions & Folder Structure (JavaScript/Node.js)

📜 Most Used and Important Categories

✅ Configuration (config/)

  • Description: Stores application-level configurations, environment variables, and settings.
  • Suffix/Prefix: Config
  • Example File: config/app.config.js

Code Example:

const AppConfig = {
    DATABASE_URL: "postgresql://user:password@localhost/db_name",
    SECRET_KEY: "mysecretkey",
    DEBUG: true
};

module.exports = AppConfig;

✅ Models (models/)

  • Description: Defines database schemas.
  • Suffix/Prefix: Model
  • Example File: models/auth.model.js

Code Example:

const mongoose = require("mongoose");

const AuthSchema = new mongoose.Schema({
    email: { type: String, required: true, unique: true },
    password: { type: String, required: true }
});

module.exports = mongoose.model("Auth", AuthSchema);

✅ Repository (repositories/)

  • Description: Handles all database interactions such as CRUD operations.
  • Suffix/Prefix: Repository
  • Example File: repositories/auth.repository.js

Code Example:

class AuthRepository {
    async createUser(user) {
        // Logic for creating a user
    }

    async getUserById(userId) {
        // Logic for fetching user by ID
    }
}

module.exports = new AuthRepository();

✅ Service (services/)

  • Description: Contains business logic.
  • Suffix/Prefix: Service
  • Example File: services/auth.service.js

Code Example:

const AuthRepository = require("../repositories/auth.repository");

class AuthService {
    async login(email, password) {
        // Authentication logic
    }

    async register(user) {
        // Registration logic
    }
}

module.exports = new AuthService();

✅ Controller (controllers/)

  • Description: Handles incoming HTTP requests.
  • Suffix/Prefix: Controller
  • Example File: controllers/auth.controller.js

Code Example:

const express = require("express");
const AuthService = require("../services/auth.service");

const router = express.Router();

router.post("/login", async (req, res) => {
    // Login logic
});

router.post("/register", async (req, res) => {
    // Registration logic
});

module.exports = router;

✅ Middleware (middlewares/)

  • Description: Handles request interception.
  • Suffix/Prefix: Middleware
  • Example File: middlewares/auth.middleware.js

Code Example:

module.exports = (req, res, next) => {
    // Authentication middleware logic
    next();
};

✅ Utilities (utils/)

  • Description: Helper functions.
  • Suffix/Prefix: Utils
  • Example File: utils/password.utils.js

Code Example:

const bcrypt = require("bcrypt");

class PasswordUtils {
    static hashPassword(password) {
        return bcrypt.hash(password, 10);
    }
}

module.exports = PasswordUtils;

3. Professional Folder Structure (Express.js)

project_root/
│── src/
│   ├── controllers/        # Handles HTTP requests
│   ├── services/           # Business logic layer
│   ├── repositories/       # Database interaction layer
│   ├── models/             # Data models and ORM schemas
│   ├── middlewares/        # Request interception & processing
│   ├── utils/              # Helper functions and utilities
│── config/                 # Configuration files and environment settings
│── routes/                 # Defines API routes
│── tests/                  # Unit and integration tests
│── docs/                   # Project documentation
│── logs/                   # Log files
│── scripts/                # Deployment and automation scripts
│── package.json            # Dependencies
│── .env                    # Environment variables
│── README.md               # Project overview and usage instructions

4. Function & Variable Naming Rules

Function Naming:

  • Use camelCase for function names: getUserById()
  • Start function names with verbs that describe the action:
  • fetchUsers()
  • calculateDiscount()
  • validateEmail()
  • Private/internal functions should start with an underscore: _hashPassword()
  • Use clear and descriptive names:
  • sendVerificationEmail()
  • getUserProfileData()

Variable Naming:

  • Use camelCase for variables:
  • userName = "Jay Patel"
  • totalAmount = 500
  • Use descriptive names, avoid single-letter variables (except for loop counters):
  • u = getUser() ❌ (not clear)
  • user = getUser()
  • Boolean variables should start with is, has, or can:
  • isActive = true
  • hasPermission = false
  • Use plural names for collections:
  • userList = []
  • products = {}

This ensures clean and scalable project structures! 🚀