002_Good_Programming_Practice
002_Good_Programming_Practice
Readable Code
1. Naming Conventions
o Use meaningful and descriptive names for variables, methods, and classes.
o Follow standard naming conventions (e.g., camelCase for variables, PascalCase for
classes).
o Examples:
▪ Bad: calcTP, OD
2. Comments
o Use single-line comments (//) for small explanations and multi-line comments (/* */)
for detailed descriptions.Examples:
o /*
o */
updateUserData(user);
Maintainable Code
1. Remove Hardcoded Constants
o Example:
o // Bad Practice
o // Good Practice
Modular Code
1. Introduction to Subroutines
o Example:
o Well-documented behavior.
o Example:
o if denominator == 0:
o Example:
o def get_user_data(user_id):
o if not user_exists(user_id):
return fetch_user_data(user_id)
1. Coupling
o Example:
o class EmailService:
o ...
o class NotificationMnager:
self.email_service.send_email(user.email, message)n.
2. Cohesion
o Cohesion measures how closely related the tasks within a module are.
Robust Program
o Correctness: : Ensures the program produces expected output for valid inputs.
o Robustness.
o Example:
o try:
o data = read_file("config.json")
o except FileNotFoundError:
create_default_config()
2. Maintainable Code
3. Modular Code
o Write a program to manage a library system using subroutines for adding, deleting,
and searching books.
Advanced Assignments
o Analyze a provided code snippet and suggest improvements for readability and
maintainability.
o Design a shopping cart module with low coupling and high cohesion.
3. Robust Program
o Develop a file parser that handles edge cases like missing files, corrupted data, and
unexpected formats.
1. What is the difference between low coupling and high cohesion? Why are they important?
o Answer: Low coupling ensures modules are independent, making the system easier
to maintain and test. High cohesion ensures modules focus on a single task,
improving readability and reusability.
o Answer: Correctness ensures expected output for valid inputs, while robustness
handles invalid inputs gracefully. For example, a correct program might fail on
invalid input, whereas a robust program will catch the error and log it.
o Answer: Clear name, single responsibility, minimal and validated arguments, no side
effects, and meaningful return values.