Published on

Clean and maintable code

Authors
  • avatar
    Name
    Loc Truong
    Twitter

Consistent Code Formatting

Meaningful Variable Names and Comments

// Avoid
let c = 10; // Avoid using single-letter variable names
let func = () => {
    // Complex logic without explanation
};

// Prefer
const itemCount = 10; // Use descriptive variable names
const calculateTotal = () => {
    // Clear function name and comments for complex logic
};
def calculate_discount(price):
  TEN_PERCENT_DISCOUNT = 0.1
  discount = price * TEN_PERCENT_DISCOUNT
  return price - discount

def calculate_discount(product_price):
  """Calculate discount for product.

   Warning: Certain characters might not be handled correctly.
   Please refer to the documentation for supported formats.

   Args:
       product_price (float): The price of the product.

   Returns:
       Float: The calculated discount price. 

   Raises:
       ValueError: If the product price is invalid or unsupported.
  """
  TEN_PERCENT_DISCOUNT = 0.1
  discount_amount = product_price * TEN_PERCENT_DISCOUNT
  return product_price - discount_amount

Modularization and Single Responsibility Principle (SRP)

// Avoid
const handleUserData = () => {
    // Performs multiple tasks: fetches data, processes it, and updates UI
};

// Prefer
const fetchData = () => {
    // Responsible for fetching data
};
const processData = (data) => {
    // Responsible for processing data
};
const updateUI = (processedData) => {
    // Responsible for updating the UI
};
def process_data(data):
   # ... validate users...
   # ... calculate values ...
   # ... format output …

def validate_user(data):
   # ... data validation logic ...
def calculate_values(data):
   # ... calculation logic based on validated data ...
def format_output(data):
   # ... format results for display …

Avoid Magic Numbers and Strings

// Avoid
if (status === 2) {
    // What does 2 signify?
    // ...
}

// Prefer
const STATUS_COMPLETED = 2;
if (status === STATUS_COMPLETED) {
    // Clear and self-explanatory
    // ...        
}

Follow the DRY (Don't Repeat Yourself) Principle and Avoid Duplicating Code or Logic

def calculate_book_price(quantity, price):
  return quantity * price
def calculate_laptop_price(quantity, price):
  return quantity * price

def calculate_product_price(product_quantity, product_price):
 return product_quantity * product_price

Error Handling and Graceful Degradation

const fetchData = async (url) => {
    try {
        const response = await fetch(url);
        if (!response.ok) {
            throw new Error('Failed to fetch data');
        }
        return await response.json();
    } catch (error) {
        console.error('Error fetching data:', error.message);
       return null;
    }
};

Testing and Continuous Integration (CI)

Write comprehensive unit tests using tools like Jest or Mocha to validate your code's functionality. Integrate these tests into your CI/CD pipeline to catch issues early and ensure code quality.

Version Control and Documentation

Utilize version control systems like Git and maintain descriptive commit messages. Document your code, APIs, and functions using tools like JSDoc to assist developers in understanding its purpose and usage.