0% found this document useful (0 votes)
2 views

002_Good_Programming_Practice

The document outlines good programming practices focusing on readable, maintainable, and modular code. It emphasizes the importance of naming conventions, comments, and guidelines for writing code, as well as the concepts of coupling and cohesion. Additionally, it includes assignments for practice and interview questions related to these practices.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

002_Good_Programming_Practice

The document outlines good programming practices focusing on readable, maintainable, and modular code. It emphasizes the importance of naming conventions, comments, and guidelines for writing code, as well as the concepts of coupling and cohesion. Additionally, it includes assignments for practice and interview questions related to these practices.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Good Programming Practices

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 Avoid abbreviations unless they are widely understood.

o Examples:

▪ Good: calculateTotalPrice, OrderDetails

▪ Bad: calcTP, OD

2. Comments

o Write comments to explain the purpose of code, especially complex logic.

o Avoid redundant comments that merely restate the code.

o Use single-line comments (//) for small explanations and multi-line comments (/* */)
for detailed descriptions.Examples:

o // Calculate the total price including tax

o double totalPrice = basePrice + tax;

o /*

o Updateuser data in the database:

o - Save changes to name, email, and password.

o - Ensure all validations pass.

o */

updateUserData(user);

3. Guidelines for Writing Good Code

o Follow consistent formatting (indentation, spacing).

o Limit line length (e.g., 80-120 characters).

o Avoid deeply nested structures; refactor into smaller functions if necessary.

o Ensure code readability by structuring logical blocks clearly.

Maintainable Code
1. Remove Hardcoded Constants

o Define constants as variables or configuration files.

o Use descriptive names for constants (e.g., MAX_RETRY_COUNT instead of 3).

o Example:

o // Bad Practice

o if (score > 50) { ... }

o // Good Practice

o const PASSING_SCORE = 50;

if (score > PASSING_SCORE) { ... }

o Maintain constants in a centralized configuration file for scalability.

Modular Code

1. Introduction to Subroutines

o Subroutines, or functions, break down tasks into smaller, reusable components.

o Each subroutine should perform a single, well-defined task.

o Example:

o def calculate_area(length, width):

return length * width

2. Characteristics of Well-Defined Subroutines

o Clear and descriptive names.

o Minimal arguments; use objects or structures if necessary.

o Well-documented behavior.

3. Best Practices for Subroutines

o Keep subroutines small (e.g., 20-30 lines).

o Avoid side effects; do not modify global variables.

o Ensure each subroutine has a single responsibility.

4. Guidelines for Arguments

o Use a consistent order for arguments (e.g., input, processing, output).

o Pass arguments by value or reference based on requirements.


o Validate arguments to prevent invalid inputs.

o Example:

o def divide_numbers(numerator, denominator):

o if denominator == 0:

o raise ValueError("Denominator cannot be zero.")

return numerator / denominator

5. Best Practices for Return Values

o Return meaningful values or objects.

o Avoid returning magic numbers or null; use exceptions if necessary.

o Example:

o def get_user_data(user_id):

o if not user_exists(user_id):

o raise UserNotFoundError("User not found.")

return fetch_user_data(user_id)

Coupling and Cohesion

1. Coupling

o Coupling refers to the degree of dependency between modules.

o Aim for low coupling by minimizing inter-module dependencies.

o Example: Use interfaces or dependency injectioTechniques:

▪ Use interfaces or dependency injection.

▪ Abstract away implementation details using design patterns.

o Example:

o # Low Coupling Example

o class EmailService:

o def send_email(self, recipient, message):

o ...

o class NotificationMnager:

o def __init__(self, email_service):


o self.email_service = email_service

o def notify_user(self, user, message):

self.email_service.send_email(user.email, message)n.

2. Cohesion

o Cohesion measures how closely related the tasks within a module are.

o High cohesion ensures that a module focuses on a single responsibility.

o Example: A UserManager moduhandlesle should handle user-related operatiolike


create_user, delete_user, update_user.

o Low Cohesion: A MiscUtilities module performs unrelated tasks like


generate_report, send_email, process_payments.ns only.

Robust Program

1. Difference Between Correctness and Robustness

o Correctness: : Ensures the program produces expected output for valid inputs.

o Robustness.

o Robustness: : Ensures the program handles invalid inputs or unexpected situations


gracefully.

2. Tips for Robustness

o Validate inputs rigorously.

o Handle exceptions using try-catch blocks.

o Test edge cases and stress-test the program.

o Use logging to record unexpected events for debugging.

o Example:

o try:

o data = read_file("config.json")

o except FileNotFoundError:

o log_error("Configuration file missing.")

create_default_config()

Good Programming PracticAssignmentseBasic Assignmentss

Let me know if you need further adjustments or additional content!


1. Readable Code

o Write a program to calculate the factorial of a number using clear naming


conventions and proper comments.

2. Maintainable Code

o Refactor a provided program to replace hardcoded values with constants.

3. Modular Code

o Write a program to manage a library system using subroutines for adding, deleting,
and searching books.

Advanced Assignments

1. Readable and Maintainable Code

o Analyze a provided code snippet and suggest improvements for readability and
maintainability.

2. Coupling and Cohesion

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.

Interview Questions and Answers

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.

2. How do you ensure your code is maintainable?

o Answer: By using meaningful naming conventions, avoiding hardcoded values,


writing modular code, and adhering to coding standards.

3. What is the difference between correctness and robustness? Provide examples.

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.

4. What are the characteristics of a well-defined subroutine?

o Answer: Clear name, single responsibility, minimal and validated arguments, no side
effects, and meaningful return values.

5. What are some best practices for writing comments?


o Answer: Comments should explain why the code exists, not what it does. Avoid
redundant comments and update comments when the code changes.

You might also like