Lecture Notes Of Class 7: Writing Code Following Coding Standards

Lecture Notes Of Class 7: Writing Code Following Coding Standards

Objective:

To understand the importance of following coding standards and learn how to write clean, readable, and maintainable code.

Introduction

Coding standards are a set of guidelines used to write consistent, readable, and maintainable code. Following these standards ensures that:

  • The code is easy to understand for other developers.
  • It reduces errors and improves debugging.
  • It helps in maintaining and scaling the project.
  • The development process becomes more efficient and organized.

1. Overview of Clean Code Principles

Writing clean code means writing code that is easy to read, understand, and modify. Here are some key principles:

1.1 Meaningful Naming Conventions

Bad Example:

php
CopyEdit
$a = 10;
$b = 20;
$c = $a + $b;
echo $c;

Good Example:

php
CopyEdit
$firstNumber = 10;
$secondNumber = 20;
$sum = $firstNumber + $secondNumber;
echo $sum;
  • Variables, functions, and classes should have descriptive names.
  • Avoid using single-letter variable names unless they are loop counters.

1.2 Proper Indentation and Formatting

Proper indentation improves the readability of code.

Bad Example (No indentation, messy code):

php
CopyEdit
function add($a,$b){return$a+$b;}

Good Example (Proper indentation, readable):

php
CopyEdit
function add($a, $b) {
    return $a + $b;
}
  • Use consistent indentation (spaces or tabs).
  • Keep the code properly structured for readability.

1.3 Keeping Functions Small and Focused

Functions should perform a single task and should not be too lengthy.

Bad Example (Doing multiple things in one function):

php
CopyEdit
function processUser($name, $email) {
    echo "User: $name, Email: $email";
    $timestamp = date("Y-m-d H:i:s");
    file_put_contents("log.txt", "$name - $email - $timestamp\n", FILE_APPEND);
}

Good Example (Separate responsibilities into functions):

php
CopyEdit
function logUser($name, $email) {
    $timestamp = date("Y-m-d H:i:s");
    file_put_contents("log.txt", "$name - $email - $timestamp\n", FILE_APPEND);
}
 
function displayUser($name, $email) {
    echo "User: $name, Email: $email";
}
 
// Usage
$name = "John Doe";
$email = "john@example.com";
displayUser($name, $email);
logUser($name, $email);
  • Each function should have a single responsibility.
  • Breaking tasks into multiple functions makes code more modular and reusable.

1.4 Using Comments Wisely

Bad Example (Unnecessary comments):

php
CopyEdit
$x = 10; // Assigning value 10 to x
$y = 20; // Assigning value 20 to y
$sum = $x + $y; // Adding x and y

Good Example (Clear and meaningful comments):

php
CopyEdit
// Calculate the sum of two numbers
$sum = $firstNumber + $secondNumber;
  • Write comments only where necessary.
  • Avoid stating obvious things in comments.
  • Use comments to explain the "why" rather than "what".

1.5 Avoiding Hardcoded Values

Bad Example:

php
CopyEdit
$tax = 0.18
$finalAmount = $amount + ($amount * 0.18);

Good Example:

php
CopyEdit
define("TAX_RATE", 0.18);
$finalAmount = $amount + ($amount * TAX_RATE);
  • Use constants for values that do not change.
  • This improves code reusability and maintainability.

2. Hands-on Practice with Writing Code That Follows Best Practices

Task 1: Refactor the Given Code

Original Code (Messy and hard to read):

php
CopyEdit
function calc($a,$b,$op){
if($op=="+"){return$a+$b;}
elseif($op=="-"){return$a-$b;}
elseif($op=="*"){return$a*$b;}
elseif($op=="/"){return$a/$b;}
else{return"Invalid Operation";}
}

Refactored Code (Clean and Readable):

php
CopyEdit
function calculate($num1, $num2, $operator) {
    switch ($operator) {
        case '+':
            return $num1 + $num2;
        case '-':
            return $num1 - $num2;
        case '*':
            return $num1 * $num2;
        case '/':
            return $num2 != 0 ? $num1 / $num2 : "Cannot divide by zero";
        default:
            return "Invalid Operation";
    }
}

Key Improvements:

Proper variable naming
Code structure is clear
Uses switch for better readability
Includes error handling


3. Exercise: Refactor an Existing Piece of Code

Task:

You are given the following unstructured and messy code. Your task is to refactor it following coding standards.

Messy Code:

php
CopyEdit
function show($n){if($n%2==0){echo"Even";}else{echo"Odd";}}

Steps to Refactor:

1.   Rename the function to something meaningful.

2.   Use proper indentation and formatting.

3.   Add comments to explain what the function does.

Expected Refactored Code:

php
CopyEdit
// Function to check if a number is even or odd
function checkEvenOrOdd($number) {
    if ($number % 2 == 0) {
        echo "Even";
    } else {
        echo "Odd";
    }
}
 
// Example usage
checkEvenOrOdd(7);

Conclusion

Following coding standards is essential for writing clean, maintainable, and error-free code. By implementing best practices such as meaningful naming, proper indentation, modular functions, and avoiding hardcoded values, developers can improve their productivity and make code easier to understand.

Key Takeaways:
Use meaningful variable and function names.
Follow proper indentation and formatting.
Keep functions small and focused.
Write comments wisely.
Avoid hardcoded values and use constants.

Homework:

Refactor the following code to follow coding standards:

php
CopyEdit
function multiply($a,$b){return$a*$b;}

Apply the best practices learned in class to improve the code structure.

2/2

You said:

WRITE 10 ASSIGNMENTS FROM ABOVE CONCEPT WITH STEP BY STEP SOLUTIONS with proper explanation in details

ChatGPT said:

ChatGPT

Here are 10 assignments based on the topic "Writing Code Following Coding Standards" along with step-by-step solutions and explanations.


Assignment 1: Proper Naming Conventions

Problem:

Refactor the following code to follow meaningful naming conventions.

php
CopyEdit
function abc($x,$y){
    return $x*$y;
}

Solution:

Step 1: Rename the function

  • The function name abc is not meaningful.
  • Rename it to multiplyNumbers to describe its purpose.

Step 2: Rename the parameters

  • Change $x and $y to $num1 and $num2 for better readability.

Final Code:

php
CopyEdit
function multiplyNumbers($num1, $num2) {
    return $num1 * $num2;
}

Explanation:

Function name is descriptive.
Parameters are meaningful.
Code readability is improved.


Assignment 2: Proper Indentation and Formatting

Problem:

The following code lacks proper formatting. Fix it.

php
CopyEdit
function add($a,$b){return$a+$b;}

Solution:

Step 1: Add proper indentation and spacing

  • Place return on a new line.
  • Use spaces between function parameters.
  • Use a consistent code structure.

Final Code:

php
CopyEdit
function addNumbers($num1, $num2) {
    return $num1 + $num2;
}

Explanation:

Code is now well-structured and easy to read.
Consistent indentation makes it more maintainable.


Assignment 3: Keeping Functions Small and Focused

Problem:

Refactor the function to follow the Single Responsibility Principle.

php
CopyEdit
function process($name, $email) {
    echo "User: $name, Email: $email";
    file_put_contents("log.txt", "$name - $email\n", FILE_APPEND);
}

Solution:

Step 1: Separate Display and Logging Functionality

  • One function should display the user details.
  • Another function should log the user details.

Final Code:

php
CopyEdit
function displayUser($name, $email) {
    echo "User: $name, Email: $email";
}
 
function logUser($name, $email) {
    file_put_contents("log.txt", "$name - $email\n", FILE_APPEND);
}
 
// Example usage
displayUser("John Doe", "john@example.com");
logUser("John Doe", "john@example.com");

Explanation:

Each function does a single task.
Code is now modular and reusable.


Assignment 4: Using Comments Wisely

Problem:

Add proper comments to the following code.

php
CopyEdit
function check($n) {
    if($n % 2 == 0) {
        echo "Even";
    } else {
        echo "Odd";
    }
}

Solution:

Step 1: Add comments to explain the function

php
CopyEdit
// Function to check if a number is even or odd
function checkEvenOrOdd($number) {
    // If number is divisible by 2, it's even
    if ($number % 2 == 0) {
        echo "Even";
    } else {
        echo "Odd";
    }
}
 
// Example usage
checkEvenOrOdd(5);

Explanation:

Comments explain what the function does.
Code is now more understandable.


Assignment 5: Avoiding Hardcoded Values

Problem:

Remove hardcoded values from the following code.

php
CopyEdit
$tax = 0.18;
$finalAmount = $amount + ($amount * 0.18);

Solution:

Step 1: Define a Constant

php
CopyEdit
define("TAX_RATE", 0.18);
$finalAmount = $amount + ($amount * TAX_RATE);

Explanation:

Constants improve maintainability.
Changes can be made in one place.


Assignment 6: Using Switch Instead of Multiple If-Else

Problem:

Refactor the following code using switch.

php
CopyEdit
function calculate($a, $b, $op) {
    if ($op == "+") {
        return $a + $b;
    } elseif ($op == "-") {
        return $a - $b;
    } elseif ($op == "*") {
        return $a * $b;
    } elseif ($op == "/") {
        return $a / $b;
    } else {
        return "Invalid Operation";
    }
}

Solution:

php
CopyEdit
function calculate($num1, $num2, $operator) {
    switch ($operator) {
        case '+':
            return $num1 + $num2;
        case '-':
            return $num1 - $num2;
        case '*':
            return $num1 * $num2;
        case '/':
            return $num2 != 0 ? $num1 / $num2 : "Cannot divide by zero";
        default:
            return "Invalid Operation";
    }
}

Explanation:

Switch improves readability.
Handles division by zero properly.


Assignment 7: Refactoring Messy Code

Problem:

Improve the readability of the following code.

php
CopyEdit
function printMsg($msg){echo "Message: ".$msg;}

Solution:

php
CopyEdit
// Function to display a message
function printMessage($message) {
    echo "Message: " . $message;
}

Function name is now descriptive.
Proper indentation is used.


Assignment 8: Handling Errors Properly

Problem:

Modify the function to handle division by zero error.

php
CopyEdit
function divide($a, $b) {
    return $a / $b;
}

Solution:

php
CopyEdit
function divide($num1, $num2) {
    if ($num2 == 0) {
        return "Error: Cannot divide by zero";
    }
    return $num1 / $num2;
}

Prevents division by zero errors.


Assignment 9: Refactoring for Readability

Problem:

Improve the structure of the following code.

php
CopyEdit
function greet($name){echo"Hello, ".$name."!";}

Solution:

php
CopyEdit
// Function to greet a user
function greetUser($name) {
    echo "Hello, " . $name . "!";
}

Function name is clear.
Proper spacing improves readability.


Assignment 10: Refactoring a Large Function

Problem:

Split this function into smaller functions.

php
CopyEdit
function processOrder($amount) {
    echo "Processing order for amount: " . $amount;
    $tax = $amount * 0.18;
    $total = $amount + $tax;
    return $total;
}

Solution:

php
CopyEdit
function calculateTax($amount) {
    return $amount * 0.18;
}
 
function processOrder($amount) {
    $tax = calculateTax($amount);
    $total = $amount + $tax;
    return $total;
}

Function is now modular.
Easy to reuse and modify.


Conclusion

By following coding standards, we can:
Improve code readability
Enhance maintainability
Reduce errors and debugging time

These assignments will help students practice and understand clean coding principles effectively. 🚀

You said:

WRITE 50 no of MCQs only FROM ABOVE CONCEPT with explanation

ChatGPT said:

ChatGPT

Here are 50 Multiple-Choice Questions (MCQs) on the topic "Writing Code Following Coding Standards", along with explanations.


1-10: Naming Conventions

1.   Which of the following is the best variable name?
a)
$var1
b)
$x
c)
$customerName
d)
$cN
Explanation: Meaningful names improve readability.

2.   What is a good function name for calculating tax?
a)
calc()
b)
calculateTax()
c)
ctax()
d)
function1()

3.   Why should we avoid single-letter variable names?
a) They increase readability
b) They are hard to understand

c) They use less memory
d) They run faster

4.   Which naming convention is recommended for PHP variables?
a) camelCase

b) PascalCase
c) snake_case
d) UPPERCASE

5.   Which of these function names follow camelCase?
a)
CalculateTax()
b)
calculate_tax()
c)
calculateTax()
d)
calculate tax()

6.   Which of these is NOT a recommended naming convention?
a)
$totalAmount
b)
$_tempVar
c)
$t1a
d)
$user_name

7.   Which of these is a bad practice in naming variables?
a) Using meaningful names
b) Using numbers in variable names

c) Using camelCase
d) Using underscores in constants

8.   What is a good name for a boolean variable?
a)
$status
b)
$isActive
c)
$x
d)
$data1

9.   Which of these is a valid PHP constant name?
a)
$MAXVALUE
b)
MAX_VALUE
c)
MaxValue
d)
maxvalue

10.                     Which naming convention is commonly used for PHP class names?
a) camelCase
b) PascalCase

c) snake_case
d) UPPERCASE


11-20: Code Formatting & Indentation

11.                     Why is proper indentation important?
a) Improves readability

b) Reduces execution time
c) Increases file size
d) Slows down performance

12.                     What is the correct way to write a function?

php
CopyEdit
function add($a,$b){return $a+$b;}

a) Correct
b) Needs better spacing

c) Needs different naming
d) Needs different brackets

13.                     Which statement about indentation is FALSE?
a) It makes debugging easier
b) It improves collaboration
c) It speeds up execution

d) It improves readability

14.                     Which of the following is correctly formatted?
a)
if($x==1){echo "One";}
b)
if ($x == 1) { echo "One"; }
c)
if ($x == 1){echo "One";}
d)
if($x ==1) echo "One";

15.                     Which of these is bad indentation?

php
CopyEdit
function test() {echo "Hello";}

a) Needs a new line for echo
b) Needs shorter function name
c) Needs a comment
d) Needs a return value

16.                     Why should curly braces {} be properly placed?
a) Prevent syntax errors

b) Reduce execution time
c) Improve speed
d) Make variables work better

17.                     Which type of indentation is commonly used in PHP?
a) Tabs
b) Spaces
c) Both

d) No indentation required

18.                     Which is a correctly formatted if-statement?

php
CopyEdit
if ($x > 10)
{
    echo "Greater";
}

a) Correct
b) Needs more spacing
c) Needs less spacing
d) Needs a return value

19.                     What should be done if an if-else block is too long?
a) Remove spaces
b) Break into functions

c) Use fewer variables
d) Remove indentation

20.                     Which of these is an incorrect indentation?

php
CopyEdit
function greet(){
echo "Hello!";
}

a) Needs a new line for echo
b) Needs
return
c) Needs different brackets
d) Needs shorter function name


21-30: Code Readability

21.                     Why should functions be small?
a) Improves readability

b) Uses less memory
c) Executes faster
d) Increases performance

22.                     Which of these is NOT a good practice?
a) Keeping functions short
b) Using meaningful variable names
c) Writing long functions

d) Adding comments

23.                     What is the best way to improve readability?
a) Proper indentation

b) Remove spaces
c) Use short variable names
d) Avoid using functions

24.                     What does DRY stand for?
a) Don't Repeat Yourself

b) Don't Read Yet
c) Define Readable YAML
d) Debug Readable Yield

25.                     Which is a good way to refactor messy code?
a) Make functions smaller

b) Remove indentation
c) Add unnecessary variables
d) Use single-letter variables


31-40: Error Handling

31.                     What should be done before dividing two numbers?
a) Check if the denominator is zero

b) Use a global variable
c) Always divide by 2
d) Use an
else statement

32.                     Which PHP function is used for error handling?
a)
tryCatch()
b)
error_log()
c)
catchError()
d)
handleError()

33.                     Which statement handles division errors correctly?

php
CopyEdit
function divide($a, $b) {
    if ($b == 0) return "Error: Cannot divide by zero";
    return $a / $b;
}

a) Correct
b) Needs different return
c) Needs a different function name
d) Needs a while loop


41-50: Code Optimization

41.                     Why is refactoring important?
a) Improves readability

b) Increases code size
c) Slows down execution
d) Reduces indentation

42.                     What is the advantage of using constants?
a) Prevents accidental modification

b) Reduces performance
c) Uses less memory
d) Changes automatically

43.                     Which of these helps in code maintainability?
a) Modular functions

b) Hardcoded values
c) Long function names
d) Ignoring errors


These 50 MCQs cover naming conventions, formatting, indentation, readability, error handling, and optimization with detailed explanations! 🚀

You said:

rest

ChatGPT said:

ChatGPT

Here are the remaining Multiple-Choice Questions (MCQs) on the topic "Writing Code Following Coding Standards", with explanations.


31-40: Error Handling (Continued)

31.                     What is the primary purpose of error handling?
a) To stop execution when an error occurs
b) To provide meaningful error messages and prevent crashes

c) To make debugging harder
d) To ignore errors

32.                     Which PHP function is used to throw a custom error message?
a)
throw new Exception()
b)
catchError()
c)
error_throw()
d)
tryCatch()

33.                     Which keyword is used in PHP to handle exceptions?
a)
try...catch
b)
if...else
c)
switch
d)
throw new

34.                     What should you do when catching an exception?
a) Ignore it
b) Log it for debugging

c) Crash the application
d) Remove the
catch block

35.                     Why should error reporting be disabled in production?
a) To improve speed
b) To prevent security risks

c) To make errors disappear
d) To make debugging easier

36.                     Which PHP function can be used to log errors into a file?
a)
error_log()
b)
logError()
c)
catchError()
d)
writeError()

37.                     What does the finally block do in PHP exception handling?
a) Executes whether an error occurs or not

b) Stops execution
c) Catches exceptions
d) Ignores exceptions

38.                     Which function is used to set a custom error handler in PHP?
a)
set_error_handler()
b)
handle_errors()
c)
error_catch()
d)
catch_exception()

39.                     Which of these is an example of proper error handling?

php
CopyEdit
try {
    $result = divide(10, 0);
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

a) Correct
b) Needs a different function name
c) Needs more comments
d) Needs a loop

40.                     What happens if an exception is not caught in PHP?
a) The script continues execution
b) The script stops with a fatal error

c) The script ignores the error
d) The script automatically fixes the error


41-50: Code Optimization & Maintainability

41.                     Which principle states that code should be written once and reused?
a) DRY (Don't Repeat Yourself)

b) WET (Write Everything Twice)
c) YAGNI (You Ain’t Gonna Need It)
d) KISS (Keep It Simple, Stupid)

42.                     What is refactoring?
a) Improving code without changing functionality

b) Deleting unused files
c) Adding new features
d) Changing programming languages

43.                     Which of these is a good refactoring practice?
a) Splitting large functions into smaller ones

b) Using long variable names
c) Writing more comments instead of simplifying code
d) Removing indentation

44.                     What is the benefit of writing modular functions?
a) Improves code reusability

b) Makes debugging harder
c) Increases file size
d) Slows down performance

45.                     Which of these helps improve code maintainability?
a) Writing self-explanatory function names

b) Using global variables everywhere
c) Hardcoding values
d) Avoiding comments

46.                     What does KISS stand for in programming?
a) Keep It Simple, Stupid

b) Keep It Secure & Safe
c) Keep It Short & Smart
d) Keep It Syntactically Strong

47.                     Why should global variables be avoided?
a) They are hard to debug

b) They increase execution speed
c) They use less memory
d) They are easy to manage

48.                     What is the best way to improve performance in a loop?
a) Reduce unnecessary computations inside the loop

b) Add more function calls inside the loop
c) Increase loop iterations
d) Use global variables

49.                     Which of the following should be used to define a constant in PHP?
a)
define("SITE_NAME", "MyWebsite");
b)
$SITE_NAME = "MyWebsite";
c)
const SITE_NAME = "MyWebsite";
d)
constant("SITE_NAME", "MyWebsite");

50.                     Which of these is NOT a benefit of following coding standards?
a) Makes code easier to read
b) Helps in debugging
c) Slows down execution

d) Improves collaboration


  

Comments