Junior
What is the DRY principle and what aspects does it include?
sobes.tech AI
Answer from AI
The DRY principle (Don't Repeat Yourself) — do not repeat yourself. It is a fundamental software development principle aimed at reducing code and data redundancy. Following it increases maintainability, readability, and reduces the likelihood of errors.
Aspects of the DRY principle:
- Avoid code duplication: Repetitive blocks of code are extracted into functions, classes, or modules.
// Bad: def process_user_data(user): print(f"Processing data for user: {user['name']}") # Lots of processing steps print("Data processing finished.") def process_order_data(order): print(f"Processing data for order: {order['id']}") # Lots of processing steps (similar to user data) print("Data processing finished.") // Good: def process_data(item_type, item_id): print(f"Processing data for {item_type}: {item_id}") # Shared processing steps print("Data processing finished.") process_data("user", user['name']) process_data("order", order['id']) - Avoid data duplication: The same information is stored in one place (e.g., configuration parameters, constants).
// Bad: { "api_url_users": "https://api.example.com/users", "api_url_orders": "https://api.example.com/orders" } // Good: { "base_api_url": "https://api.example.com", "endpoints": { "users": "/users", "orders": "/orders" } } - Avoid business logic duplication: Rules and algorithms are implemented once.
// Bad: // Validation in multiple places if (orderAmount < 0) { throw new InvalidOrderException("Amount cannot be negative."); } // Similar check in another service // Good: // Centralized validation logic public void validateOrderAmount(double amount) { if (amount < 0) { throw new InvalidOrderException("Amount cannot be negative."); } } - Avoid configuration duplication: Application settings are extracted into configuration files or centralized stores.
- Avoid documentation duplication: Information is structured and references a single source.
Adhering to DRY leads to more modular, easily readable, and scalable systems, which is critical for QA as it simplifies testing and defect localization.