Table of Contents

    Practice Assignment: Improve Bad Code

    Programming Mastery

    Practice Assignment: Improve Bad Code

    Practice identifying bad code, improving readability, applying clean code principles, reducing duplication, and refactoring code without changing its original behavior.

    Assignment Overview

    In this practice assignment, students will improve poorly written code by applying the software development practices learned in previous lessons.

    The goal of this assignment is not only to make the code work, but to make the code easier to read, understand, test, review, reuse, and maintain.

    Bad code may work today, but clean code is easier to maintain tomorrow.

    Students must carefully study each bad code example, identify the problems, and rewrite the code using better naming, formatting, functions, comments, validation, and reusable structure.

    Learning Objectives

    After completing this assignment, students should be able to:

    What Students Will Practice

    • Identify poor variable and function names.
    • Improve code readability and formatting.
    • Break long or confusing logic into smaller steps.
    • Remove duplicate code using reusable functions.
    • Apply clean code basics in practical examples.
    • Use meaningful comments only where needed.
    • Handle invalid input and edge cases.
    • Write simple test cases for improved code.
    • Review code using a basic code review checklist.
    • Refactor code without changing the intended behavior.

    Instructions for Students

    Read each task carefully. Each task contains a bad code example written in language-neutral pseudocode.

    Your job is to rewrite the code in a cleaner and more professional way.

    Assignment Rules

    • Do not change the main purpose of the program.
    • Use meaningful names for variables and functions.
    • Use proper indentation and spacing.
    • Break repeated logic into reusable functions.
    • Keep functions small and focused.
    • Add validation where the task asks for it.
    • Add comments only when they explain useful context.
    • Write at least three test cases for each task.
    • Prepare a short note explaining what you improved.

    Clean Code Checklist

    Use this checklist before submitting your assignment.

    Checkpoint Question to Ask
    Meaningful Names Are variables and functions named clearly?
    Formatting Is the code properly indented and easy to scan?
    Small Functions Can large logic be divided into smaller functions?
    No Duplication Is repeated logic moved into reusable code?
    Validation Are invalid inputs handled where required?
    Comments Are comments useful and not just repeating the code?
    Testing Are normal, invalid, and boundary test cases included?
    Behavior Does the improved code still solve the same problem?

    Task 1: Improve Variable Names

    Problem Description

    The following code calculates the final bill amount after applying a discount. However, the variable names are unclear.

    Bad Code

    a = 1000
    b = 100
    c = a - b
    
    DISPLAY c

    Your Task

    • Rename all variables using meaningful names.
    • Format the code properly.
    • Make the code easy to understand without comments.
    • Do not change the calculation logic.

    Required Test Cases

    Test Case Input Expected Output
    TC_001 Bill amount 1000, discount 100 900
    TC_002 Bill amount 500, discount 50 450
    TC_003 Bill amount 800, discount 0 800

    Task 2: Improve Formatting and Readability

    Problem Description

    The following code checks whether a student passed or failed. The code works, but it is hard to read because everything is written in one line.

    Bad Code

    marks=45 IF marks>=40 THEN DISPLAY "Pass" ELSE DISPLAY "Fail" END IF

    Your Task

    • Apply proper spacing around operators.
    • Use proper indentation.
    • Write the conditional logic in a clean multi-line format.
    • Use a meaningful variable name if needed.
    • Do not change the output behavior.

    Required Test Cases

    Test Case Input Marks Expected Output
    TC_001 45 Pass
    TC_002 40 Pass
    TC_003 39 Fail

    Task 3: Remove Duplicate Code

    Problem Description

    The following code calculates the average marks of three students. The same calculation logic is repeated multiple times.

    Bad Code

    student1Total = 80 + 70 + 90
    student1Average = student1Total / 3
    DISPLAY student1Average
    
    student2Total = 60 + 75 + 65
    student2Average = student2Total / 3
    DISPLAY student2Average
    
    student3Total = 95 + 85 + 90
    student3Average = student3Total / 3
    DISPLAY student3Average

    Your Task

    • Create a reusable function to calculate average marks.
    • Use the function for all three students.
    • Use meaningful names.
    • Reduce repeated logic.
    • Keep the output same as the original program.

    Required Test Cases

    Test Case Input Marks Expected Average
    TC_001 80, 70, 90 80
    TC_002 60, 75, 65 66.67 approximately
    TC_003 95, 85, 90 90

    Task 4: Improve Function Naming and Output

    Problem Description

    The following function checks whether a student passed or failed, but the function name, parameter name, and return values are unclear.

    Bad Code

    FUNCTION calc(m)
        IF m >= 40 THEN
            RETURN "P"
        ELSE
            RETURN "F"
        END IF
    END FUNCTION

    Your Task

    • Rename the function using a meaningful name.
    • Rename the parameter using a meaningful name.
    • Return Pass and Fail instead of unclear short forms.
    • Add validation for marks below 0 or above 100.
    • Keep the function focused on one responsibility.

    Required Test Cases

    Test Case Input Marks Expected Output
    TC_001 75 Pass
    TC_002 40 Pass
    TC_003 39 Fail
    TC_004 -5 Invalid marks
    TC_005 105 Invalid marks

    Task 5: Break a Long Function into Smaller Functions

    Problem Description

    The following function does too many things. It calculates subtotal, discount, tax, and final bill amount inside one large function.

    Bad Code

    FUNCTION processBill(price, quantity)
        subtotal = price * quantity
    
        IF subtotal > 1000 THEN
            discount = subtotal * 10 / 100
        ELSE
            discount = 0
        END IF
    
        amountAfterDiscount = subtotal - discount
        tax = amountAfterDiscount * 5 / 100
        finalAmount = amountAfterDiscount + tax
    
        DISPLAY finalAmount
    END FUNCTION

    Your Task

    • Break the function into smaller reusable functions.
    • Create a function for calculating subtotal.
    • Create a function for calculating discount.
    • Create a function for calculating tax.
    • Create a function for calculating final bill amount.
    • Use meaningful names for all functions and variables.
    • Add validation for price and quantity.

    Required Test Cases

    Test Case Input Expected Result
    TC_001 price = 500, quantity = 2 No discount because subtotal is 1000
    TC_002 price = 600, quantity = 2 10% discount because subtotal is 1200
    TC_003 price = 0, quantity = 2 Invalid price
    TC_004 price = 500, quantity = 0 Invalid quantity

    Task 6: Improve Deeply Nested Code

    Problem Description

    The following code checks user login access, but it uses deep nesting. Deep nesting makes code difficult to read and maintain.

    Bad Code

    IF userExists THEN
        IF passwordCorrect THEN
            IF accountActive THEN
                IF hasPermission THEN
                    DISPLAY "Access granted"
                ELSE
                    DISPLAY "Permission denied"
                END IF
            ELSE
                DISPLAY "Account inactive"
            END IF
        ELSE
            DISPLAY "Invalid password"
        END IF
    ELSE
        DISPLAY "User not found"
    END IF

    Your Task

    • Rewrite the code to reduce deep nesting.
    • Use early checks where appropriate.
    • Keep each error message clear.
    • Make the code easier to read from top to bottom.
    • Do not change the final behavior.

    Required Test Cases

    Test Case Condition Expected Output
    TC_001 User does not exist User not found
    TC_002 Password incorrect Invalid password
    TC_003 Account inactive Account inactive
    TC_004 No permission Permission denied
    TC_005 All conditions valid Access granted

    Task 7: Improve Comments

    Problem Description

    The following code contains too many obvious comments. Good comments should explain useful context, not repeat every line.

    Bad Code

    // Set subtotal
    subtotal = 1000
    
    // Set discount
    discount = 100
    
    // Subtract discount from subtotal
    amount = subtotal - discount
    
    // Calculate tax
    tax = amount * 5 / 100
    
    // Add tax
    finalAmount = amount + tax
    
    DISPLAY finalAmount

    Your Task

    • Remove obvious comments.
    • Use meaningful variable names.
    • Add only one useful comment explaining the business rule.
    • Improve readability using spacing and structure.

    Business Rule

    Discount must be applied before tax because tax is calculated on the discounted amount.

    Task 8: Improve Code and Add Unit Test Ideas

    Problem Description

    The following function calculates discount, but it does not validate input and the naming is not clear.

    Bad Code

    FUNCTION d(a, b)
        RETURN a * b / 100
    END FUNCTION

    Your Task

    • Rename the function clearly.
    • Rename the parameters clearly.
    • Add validation for negative amount.
    • Add validation for discount percentage below 0 or above 100.
    • Write at least five unit test ideas.

    Required Unit Test Ideas

    Test Case Input Expected Output
    TC_001 amount = 1000, discount = 10 100
    TC_002 amount = 500, discount = 0 0
    TC_003 amount = 500, discount = 100 500
    TC_004 amount = -500, discount = 10 Invalid amount
    TC_005 amount = 500, discount = 120 Invalid discount percentage

    Final Assignment Deliverables

    Students must submit the following items.

    Submission Requirements

    • Improved version of all bad code examples.
    • Short explanation of what was wrong in each bad code example.
    • Short explanation of what was improved.
    • At least three test cases for each task.
    • A clean code checklist filled for the final submission.
    • Optional: peer review comments from another student.

    Assignment Review Checklist

    Before submitting, students should review their own work using this checklist.

    Review Point Done?
    All variable names are meaningful. Yes / No
    All function names clearly describe their task. Yes / No
    Code indentation is clean and consistent. Yes / No
    Repeated code has been replaced with reusable functions. Yes / No
    Large functions have been divided into smaller functions. Yes / No
    Invalid input is handled where required. Yes / No
    Unnecessary comments have been removed. Yes / No
    Useful comments explain business rules or important decisions. Yes / No
    Test cases include normal, boundary, and invalid inputs. Yes / No
    The improved code still follows the original requirement. Yes / No

    Grading Rubric

    The assignment can be evaluated using the following rubric.

    Criteria Marks Expectation
    Meaningful Naming 15 Variables and functions clearly explain purpose.
    Formatting and Readability 15 Code is properly indented, spaced, and easy to scan.
    Code Reusability 15 Repeated logic is moved into reusable functions.
    Function Design 15 Functions are small, focused, and clear.
    Validation and Edge Cases 15 Invalid and boundary cases are handled properly.
    Comments and Documentation 10 Comments are useful and not excessive.
    Testing 10 Test cases cover normal, boundary, and invalid scenarios.
    Explanation 5 Student explains what was improved and why.

    Bonus Challenge

    Students who want extra practice can complete the following bonus challenge.

    Improve one bad code example from your own previous assignments. Rewrite it using clean code principles and explain the changes.

    Bonus Requirements

    • Select one old piece of code written by you.
    • Identify at least five code quality problems.
    • Improve names, formatting, structure, and validation.
    • Add or update test cases.
    • Write a short before-and-after explanation.

    Reflection Questions

    Answer the following reflection questions after completing the assignment.

    1

    Which bad code example was easiest to improve?

    Explain why it was easy and what changes you made.

    2

    Which bad code example was most difficult?

    Explain what made it difficult and how you solved it.

    3

    What clean code principle helped you the most?

    Choose from naming, formatting, reusable functions, comments, testing, or refactoring.

    4

    How did test cases help you?

    Explain how testing helped confirm that your improved code still worked correctly.

    5

    What will you do differently in future coding assignments?

    Write two or three clean coding habits you will follow regularly.

    Expected Learning Outcome

    By the end of this assignment, students should understand that improving bad code is not only about making it shorter. Good code should be clear, organized, meaningful, testable, and easy for other developers to understand.

    Final Takeaway

    Improving bad code is an important professional programming skill. Students should learn to identify unclear names, messy formatting, repeated logic, long functions, poor comments, missing validation, and weak test coverage. The goal of refactoring is to improve code quality without changing the intended behavior. Clean code saves time, reduces bugs, improves teamwork, and makes software easier to maintain.