CSC/ECE 517 Fall 2024 - E2478. Reimplement the Question hierarchy as Item hierarchy

From Expertiza_Wiki
Jump to navigation Jump to search

This wiki page is for the description of changes made under E2478 OSS assignment for Fall 2024, CSC/ECE 517

Expertiza

Expertiza is an open-source project built using Ruby on Rails. It provides a platform for instructors and students to manage, submit, and evaluate assignments and projects. Instructors can create, edit, and grade assignments, while students can collaborate in teams, submit their work, and review peers' submissions.

Objective

Frontend: Revamp the UI for questionnaire to be responsive and user-friendly, organising elements for better accessibility and intuitive navigation across both desktop and mobile devices. This will improve the usability and overall experience for users.

Backend: Reorganise the Question class hierarchy under a more standard Item hierarchy to accurately represent items like rubric statements that aren’t technically questions. Simplify the codebase by removing redundant partials, implementing DRY principles and switching to JSON outputs for better performance and integration with modern front-end frameworks. Implement a unified code structure for similar item types (Dropdown, MultipleChoice, Scale) to handle shared behaviours, with flexibility for differences like numeric or non-numeric sequences. Rigorous testing will ensure functionality, maintainability, and adaptability to future improvements.

Problem Statement

The current question hierarchy in Expertiza is overly complex and difficult to maintain. The frontend layout is non-responsive, with disorganised elements that hinder usability, especially on mobile devices. Additionally, the backend's Question class hierarchy, while initially structured to manage rubric items, quiz questions, and survey questions, has grown cluttered with redundant partials and complex HTML generation. The system lacks clear distinctions between question types and includes partials that no longer serve a meaningful purpose, creating inconsistency and inefficiency in both data handling and rendering logic.

Explanation of the feature

The Question class and its subclasses are pivotal components utilized in Expertiza for implementing rubric items, quiz questions, and survey questions. This feature offers a versatile framework for constructing various types of questions within the platform. The hierarchy of question types within Expertiza is delineated as follows:

  • Choice questions offer users a selection of answers to choose from, categorized into scored and unscored subtypes.
    • ScoredQuestion are assigned a point value, contributing to the final score of the questionnaire. Subtypes include:
      • Scale: Presents a set of answer options covering a range of opinions, often represented numerically.
      • Criterion: Allows setting a score value AND explaining it with a text comment.
    • UnscoredQuestion do not influence the final score of the questionnaire. Subtypes include:
      • Dropdown: Presents a list of options in a dropdown menu format.
      • Multiple Choice: Provides users with multiple options for selection, available as single-select (radio buttons) or multi-select (checkboxes).
      • Checkbox: Allows users to select multiple options from a list.
  • Text Response questions enable users to input their answers directly, bypassing predefined choices. Subtypes include:
    • Text Area: A text box with adjustable height and width.
    • Text Field: A single-line input field with fixed dimensions.
  • Upload file empowers users to upload files containing valid input to utilize as questionnaires. Additionally, users can export questionnaires to a .csv file format for further analysis and sharing.

UML diagram

Commonalities and Reimplementation Goals

Dropdown, MultipleChoice, and Scale questions share common functionality in Expertiza. They all provide users with a set of alternatives to choose from. However, they also have distinct characteristics that set them apart:

  • Commonalities:
    • Display alternatives for user selection.
    • Allow users to choose one option.
  • Differences:
    • Scale: Requires a numeric sequence of choices.
    • Dropdown and MultipleChoice: May have selections that aren't necessarily numeric.

To streamline the implementation and enhance code quality, the following goals have been outlined for reimplementation:

  • Goals:
    • Responsive UI: Reorganize frontend layout for intuitive, mobile-friendly, and accessible design.
    • Item Hierarchy Refactoring: Rename the Question hierarchy to Item to better represent items like rubric statements, and restructure related classes for clarity and consistency.
    • Code Clarity: Use clear, descriptive names for variables and methods.Add comprehensive comments for easier understanding and maintenance.
    • Efficient HTML Management: Implement partials to reduce redundancy and follow the DRY principle.
    • Robust Testing: Expand RSpec tests to cover all functionality, ensuring reliability and adaptability.

Enhancements and Additions

  • The UI enhancements focus on improving usability, accessibility, and responsiveness across devices. Elements have been reorganized for a more intuitive layout, ensuring users can easily navigate and interact with the interface on both desktop and mobile screens. Key components are now better aligned, making the UI visually cohesive and user-friendly. The design has been updated to be fully responsive, adjusting smoothly to different screen sizes and orientations, providing a seamless experience for mobile users. These improvements collectively enhance the user experience by creating a streamlined, accessible, and modern interface.
  • Further enhancements include a reorganization of the backend hierarchy to improve modularity, maintainability, and scalability. Individual rendering strategies for different item types (e.g., Dropdown, MultipleChoice, Scale, Checkbox) have been implemented to streamline the rendering process. Scored and unscored questions are now handled through a clearer separation of functionality, reducing redundancy and improving code clarity. These updates ensure seamless integration between the user interface and backend logic, enhancing the performance and usability of the system while laying a strong foundation for future improvements.

Files modified and added: Reimplementation

During the reimplementation process, files underwent modifications and additions to enhance model functionality and improve user experience. Specifically, UI files were updated to create a cleaner, more readable interface, reducing clutter for easier navigation.

Reimplemented Repository[1]

Below is a file that was modified as part of the reimplementation effort:

Phase 1:

  • reimplementation-front-end/src/pages/EditQuestionnaire/Questionnaire.tsx: Modifications were made to this file to accommodate changes in view.

Phase 2:

For Phase 2, the following files were added or modified to implement the new Item hierarchy strategies and extend the functionality:

New or Updated Files

  • 1. Item.rb
    • Base class for the newly structured item hierarchy.
  • 2. Checkbox.rb
    • Implements behavior for checkbox-based items.
  • 3. Item Folder
    • Contains individual rendering strategies:
    • choice_rendering_strategy.rb
    • multiple_choice_rendering_strategy.rb
    • scale_rendering_strategy.rb
    • dropdown_rendering_strategy.rb
  • 4. QuizQuestion.rb
    • Extends functionality for quiz questions.
  • 5. Scale.rb
    • Handles the scale item type.
  • 6. ScoredQuestion.rb
    • Encapsulates logic for scored questions.
  • 7. UnscoredQuestion.rb
    • Implements logic for unscored questions.

Test Plan for Completed Enhancements

UI Enhancements Testing Summary

  • Responsiveness and Device Compatibility:
    • Test Results: Verified that the layout adjusts correctly across various screen sizes, including desktop, tablet, and mobile. Elements scale appropriately in both landscape and portrait modes on mobile, maintaining functionality and visual integrity. Confirmed that spacing and alignment remain consistent across different resolutions, achieving a cohesive and polished appearance.
  • Accessibility Verification:
    • Test Results: Ensured all interactive elements (buttons, links, forms) are accessible via keyboard navigation, supporting users with disabilities. Confirmed that elements include appropriate ARIA labels and tooltips for screen reader compatibility, enhancing accessibility. Verified that color contrast ratios for text and interactive elements meet accessibility standards, ensuring readability for all users.
  • Usability and Navigation Flow:
    • Test Results: Reorganized elements such as buttons and navigation links are now easy to locate and intuitive to use, simplifying navigation. Validated that interactions follow a logical flow, allowing users to move smoothly between pages and features. Confirmed that key actions (submit, edit, delete) are prominently positioned, making them easy to identify and enhancing overall user efficiency.
  • User Interaction Consistency:
    • Test Results: Interactive elements (buttons, dropdowns, checkboxes) display consistent feedback when hovered, clicked, or focused, ensuring a unified experience. Checked that error messages and notifications align properly and are clearly visible across all screen sizes. Verified that modals and popups open and close correctly, adapting seamlessly to different screen dimensions.
  • Performance Testing on UI Load:
    • Test Results: Measured page load times on various devices, confirming that responsiveness improvements did not impact performance. Optimized images and media elements to ensure fast loading, especially on mobile networks.
  • Validation and Error Handling:
    • Test Results:Verified that item configurations are validated correctly, ensuring invalid inputs (e.g., non-numeric values for Scale items) produce appropriate error messages. Confirmed that guard clauses prevent misconfigurations and missing properties, ensuring robust error handling.
  • Rendering Logic for Items:
    • Test Results: Ensured that rendering strategies for Dropdown, MultipleChoice, Scale, and Checkbox items work as intended, with each item type displaying correctly based on its configuration. Verified that scored and unscored questions are handled properly and that all item types maintain consistent behavior across tests.
  • Separation of Scoring Logic:
    • Test Results: Confirmed that scored items (e.g., Scale) apply numeric scoring correctly and that unscored items (e.g., Dropdown) ignore scoring logic. Validated the system’s ability to dynamically handle item properties based on item type.
  • Dynamic Item Mapping:
    • Test Results: Verified that responses are mapped correctly to item types using the unified mapping function. Ensured that all user responses are stored and processed without errors, regardless of item type.
  • Strategy Implementation Testing:
    • Test Results: Confirmed that individual rendering strategies (choice_rendering_strategy.rb, multiple_choice_rendering_strategy.rb, scale_rendering_strategy.rb, dropdown_rendering_strategy.rb) perform as expected. Verified that changes in one strategy do not affect others, ensuring modularity.
  • Performance Testing on Backend Processes:
    • Test Results: Measured processing times for rendering items and handling large questionnaires. Confirmed that the new hierarchy and strategy implementation reduce code redundancy and improve efficiency without impacting performance.

Design Document

To improve the clarity, modularity, and upkeep of the code, the project has transitioned from a Question Hierarchy to a more versatile Item Hierarchy. This restructuring emphasizes enhanced error management, the elimination of repetitive code by implementing reusable helper functions, and the division of complex workflows into smaller, purpose-specific methods. Aligned with SOLID principles and Ruby best practices, these adjustments make the codebase more accessible, adaptable, and maintainable, providing increased flexibility to accommodate a variety of item types.

Highlights of the Refactored Models:

  • Enhanced modularity using methods with well defined conventions.
  • Extensive testing across all methods and proper error handling.
  • Making use of helper methods and controllers (such as view_question_text_common) to create well structured models and methods.

Key Changes

1. Modularization of Functions:

  • Decomposition of Methods: Complex methods that previously handled specific question types (Dropdown, MultipleChoice, Scale, etc.) were split into smaller, reusable functions. For example: ​
    • render_choice_options: A helper function to handle the display of options across multiple item types.
    • validate_item_structure: Checks if each item’s structure meets the required standards.
    • ​apply_scoring_logic: Separate functions for scored items (like Scale and Criterion) and unscored items (like Dropdown), ensuring clarity in how items are evaluated.
  • Guard Clauses: Introduced guard clauses in methods to handle invalid data early, reducing nested conditionals and improving readability. For instance, render_choice_options includes guard clauses to check for missing or incompatible options.

2. Extraction of Reusable Components:

  • Unified Display Logic for Choice-Based Items: Created a single, unified function (display_choice_item) to render Dropdown, MultipleChoice, and Scale items. This function adjusts dynamically based on item type, reducing code duplication and ensuring consistency.
  • Dynamic Item Initialization: Introduced helper methods for initializing items with specific settings, e.g., initialize_scale_item and initialize_multiple_choice_item. These methods set default properties based on item type, making the item setup process simpler and more modular.
  • Separation of Scoring and Non-Scoring Logic: Extracted the logic for handling scoring items (e.g., Scale and Criterion) and non-scoring items (e.g., Dropdown) into separate helper functions. This follows the Single Responsibility Principle (SRP) and makes each function more focused.

3. Error Handling and Validation Improvements:

  • Enhanced Validation for Item Types: Added validations to ensure that each item adheres to the expected structure for its type. For example: ​
    • validate_numeric_sequence for Scale items to ensure options are sequential numbers.
    • validate_choice_format for Dropdown and MultipleChoice items to ensure the format is compatible.
  • User-Friendly Error Messages: Error messages now provide detailed feedback if an item is configured incorrectly. For instance, if a Scale item has non-numeric options, users receive a clear error message with suggestions for correction.
  • Prevention of Misconfiguration: Added checks to prevent common misconfigurations, such as assigning a CheckBox as a scoring item without specifying numeric values.

4. Automated Item Display and Rendering:

  • Helper Methods for Standardized Rendering: Created helper methods like render_item_based_on_type and generate_item_options to streamline the rendering process, making it easier to display different item types without redundant code.
  • ​Dynamic Display Based on Item Properties: Implemented a dynamic rendering strategy where each item’s display adjusts automatically based on its properties. For example, a Scale item automatically displays options in a numeric sequence, while a Dropdown item can handle both numeric and non-numeric options.
  • Customizable Templates for Item Types: Modularized the templates for different item types, allowing easy customization and addition of new item types in the future without major code modifications.

5. Automated Item Mapping and Validation:

  • ​Unified Mapping Function: Introduced a function (map_item_to_response) that standardizes the process of mapping user responses to item types, ensuring that each response is correctly matched with its respective item.
  • Flexible Item Properties Based on Type: Implemented item-specific property handling, so Scale items automatically apply numeric scoring, while TextResponse items allow free text input without scoring.
  • Strategy-Based Approach for New Item Types: Established a framework where new item types can be introduced by defining their unique properties and mappings, allowing easy extension of the item hierarchy.

These changes emphasize modularity, extensibility, and clarity, aligning with the goals of improving maintainability and usability in the Expertiza platform.

Principles Applied for Reimplementation of Question Hierarchy as Item Hierarchy

  • Single Responsibility Principle (SRP)
    • Modular Methods: Each method handles a specific task, e.g., `display_options` for rendering choices and `validate_item_properties` for checking item structures.
    • Helper Functions: Extracted distinct tasks like `render_choice_item` and `validate_numeric_sequence` to make the code easier to read and test.
  • Open/Closed Principle
    • Extensible Item Types: New item types (e.g., LikertScale) can be added without changing existing code by implementing new classes and strategies.
  • DRY (Don’t Repeat Yourself)
    • Unified Choice Display: Common rendering logic for Dropdown, MultipleChoice, and Scale items is centralized, reducing code duplication.
    • Consolidated Validation: Shared functions like `validate_choice_format` ensure consistent validation across items.
  • Error Handling
    • Validation and Guard Clauses: Improved checks for item configurations, with early exits for invalid inputs, ensuring clear errors for issues like non-numeric Scale values.

This approach enhances modularity, extensibility, and error resilience in the Item hierarchy, supporting a broader range of item types.

Design Pattern Used

The Strategy Pattern is the best choice among the provided design patterns for this task. Here’s why the Strategy Pattern is suitable and how it aligns with the requirements for the reimplementation of the Question hierarchy as an Item hierarchy:

Why Strategy Pattern?

The Strategy Pattern allows us to define a family of interchangeable behaviors (in this case, rendering options for Dropdown, MultipleChoice, and Scale items) and encapsulate each behavior in a separate class. This pattern is particularly well-suited for scenarios where we have common functionality with slight variations, as is the case with these item types. Here’s how it fits the requirements:

  • Unified Code for Similar Functionality
    • By using the Strategy Pattern, we can create a consistent interface for rendering choices, making the display logic reusable while allowing specific implementations for each item type (Dropdown, MultipleChoice, and Scale).
  • Flexibility and Extensibility
    • This pattern allows us to add or modify behavior for new or existing item types without changing the main codebase. Each new choice type would simply involve creating a new strategy class, aligning well with the Open/Closed Principle.
  • Encapsulation of Specific Behaviors
    • The Strategy Pattern helps encapsulate unique behaviors, like enforcing numeric sequences for Scale questions, while keeping the shared logic consistent across all choice-based items. This allows us to simplify the code structure and make it easy to adjust the specific requirements for each type.

How Strategy Pattern Fits with Ruby

In Ruby, the Strategy Pattern can be implemented by defining an interface (abstract class or shared method signature) and then implementing specific behaviors as separate classes. The Item class (or its choice-based subclasses) will reference a strategy for rendering options, which can be set at runtime based on the item type.

Example Implementation in Ruby

Here’s a Ruby example that uses the Strategy Pattern to handle the Dropdown, MultipleChoice, and Scale item types within the new Item hierarchy.

  # Define the common interface for display strategies
  class DisplayStrategy
   def display_options(options)
     raise NotImplementedError, "This #{self.class} cannot respond to display_options"
   end
  end
   
  # Concrete strategy for Scale items
  class ScaleStrategy < DisplayStrategy
   def display_options(options)
     # Ensure options are a numeric sequence
     options.map(&:to_i).sort
   end
  end
   
  # Concrete strategy for Dropdown items
  class DropdownStrategy < DisplayStrategy
   def display_options(options)
     # Flexible options (can be numeric or non-numeric)
     options
   end
  end

  # Concrete strategy for MultipleChoice items
  class MultipleChoiceStrategy < DisplayStrategy
   def display_options(options)
     # Flexible options (can be numeric or non-numeric)
     options
   end
  end
   
  # The main Item class with a display strategy
  class Item
   attr_accessor :display_strategy, :options
   
   def initialize(display_strategy, options)
     @display_strategy = display_strategy
     @options = options
   end
   
   def display
     display_strategy.display_options(options)
   end
  end
   
  # Example usage:
  scale_item = Item.new(ScaleStrategy.new, [1, 2, 3, 4, 5])
  puts scale_item.display # => [1, 2, 3, 4, 5]
   
  dropdown_item = Item.new(DropdownStrategy.new, ["Option A", "Option B", "Option C"])
  puts dropdown_item.display # => ["Option A", "Option B", "Option C"]
   
  multiple_choice_item = Item.new(MultipleChoiceStrategy.new, ["True", "False"])
  puts multiple_choice_item.display # => ["True", "False"]

Benefits of the Strategy Pattern for This Task

  • Modularity: Each item type’s rendering behavior is encapsulated within its own strategy class, improving modularity and readability.
  • Flexibility: The strategy object can be assigned or changed at runtime, allowing items to dynamically determine their display behavior based on type.
  • Extensibility: New item types or display styles can be added without altering the existing code, supporting the Open/Closed Principle and making the system more adaptable.

Comparison with Other Patterns

  • Visitor Pattern: Useful for performing operations across different classes but is complex for managing simple rendering behaviors and doesn’t support easy runtime changes.
  • Decorator Pattern: Suitable for adding behaviors dynamically, but the primary need here is not adding behavior dynamically but switching between predefined ones.
  • Factory/Builder Patterns: While they help with object creation, they don’t address the need for interchangeable display logic.
  • Adapter/Bridge Patterns: Useful for adapting interfaces or decoupling abstraction from implementation but less relevant here as there is no external interface or legacy code to adapt.

Conclusion

The Strategy Pattern best meets the requirements by providing a clean way to manage diverse behaviors among choice-based items in a unified structure. This pattern ensures that each item’s specific rendering needs are encapsulated, maintainable, and extensible without affecting the overall item-handling logic.

Testing improvements:

To ensure the functionality, reliability, and scalability of the new Item Hierarchy, a comprehensive testing strategy has been designed. This approach includes specific test categories, targeted scenarios, and a systematic execution process to validate both the reimplemented features and any existing functionality that may be affected by the new hierarchy. These tests are essential for enhancing the system’s robustness, maintainability, and adaptability, laying a strong foundation for future enhancements.

General Enhancements and Best Practices for Reimplementation of Question Hierarchy as Item Hierarchy

  • FactoryBot for Model Setup
    • Define models for various item types (e.g., ScaleItem, DropdownItem, TextResponseItem) in FactoryBot factories to streamline test data creation, reduce redundancy, and improve test readability.
  • Mocking and Spying
    • Use RSpec’s `allow` and `expect` methods to mock dependencies, isolating item behaviors under test and improving test performance and reliability.
  • Comprehensive Edge Case Testing
    • Test each item type for edge cases such as empty options, nil values, and invalid configurations (e.g., non-numeric values in Scale items) to ensure the system’s resilience against unexpected inputs.
  • Error Handling
    • Ensure robust handling of misconfigurations and database errors, with specific tests for invalid properties or missing data, validating the system’s stability.
  • Feedback Message Validation
    • Test for accurate and consistent feedback messages, ensuring users receive clear notifications on successful or failed actions (e.g., incorrect item setup or successful item addition).

These practices will improve code reliability, maintainability, and test coverage in the reimplemented Item hierarchy.

Test Case Categories and Example Scenarios for Reimplementation of Question Hierarchy as Item Hierarchy

  • Validation and Error Handling
    • Invalid Item Configurations: Test cases will cover scenarios where items have missing or invalid configurations, such as:
      • Non-numeric values in Scale items.
      • Empty choices in Dropdown or MultipleChoice items.
      • Unsupported file types in UploadFile items.
      • Invalid settings should result in appropriate error messages and prevent further processing.
    • Edge Cases for Error Messages: Test error messages to ensure they accurately reflect the issues, such as when trying to add a misconfigured item or edit an item with missing properties.
  • State Transitions
    • Correct Item Initialization: Tests will confirm that items initialize correctly according to their type (e.g., Scale items enforce numeric choices, TextArea items allow multi-line input).
    • Modification of Item Properties: Verify that item properties can be modified as expected, updating the system state and displaying relevant messages upon successful or failed edits.
  • Feedback Messages & Redirects
    • Successful Item Addition and Modification: Confirm that success messages appear when an item is added or updated correctly, and users are redirected to the appropriate view.
    • Error Messages for Invalid Operations: Validate that clear error messages are displayed if an item configuration is invalid or if an operation (like item deletion) cannot be completed.
  • Boundary and Edge Conditions
    • High Volume of Items: Test scenarios with a large number of items in a questionnaire or rubric (e.g., hundreds of items) to ensure that the system performs well under load without crashing or slowing down.
    • Empty Choices in Choice-Based Items: Test scenarios where choice-based items (e.g., Dropdown, MultipleChoice) have empty choice lists, ensuring the system handles this gracefully and displays appropriate warnings or error messages.
    • Invalid or Missing Item Properties: Ensure the system behaves as expected when properties required by specific item types are missing or invalid (e.g., missing numeric options for a Scale item).

These tests will ensure the Item hierarchy is robust, reliable, and capable of handling a variety of user inputs and configurations, supporting both current functionality and future scalability.

Test Execution Process for Reimplementation of Question Hierarchy as Item Hierarchy

  • Mock Dependencies
    • Use RSpec’s `allow` and `expect` methods to mock external dependencies and database interactions, focusing tests solely on item functionality without interference from other parts of the system.
  • Analyze Test Coverage
    • Assess each test case to confirm it addresses key areas of functionality, including:
    • Validation for item properties (e.g., numeric checks for Scale items).
    • State transitions, such as adding or updating items.
    • User feedback, including error messages and redirects.
    • Edge cases and boundary conditions to ensure robust error handling.
  • Run Tests Using RSpec
    • Execute the full test suite in RSpec to verify outcomes, ensuring that items initialize, validate, and render as expected. Confirm that messages and redirects work correctly for both successful and erroneous operations.
  • Evaluate Outcomes
    • Success: Verify that successful actions (like item creation and modification) trigger appropriate flash messages, redirects, and state transitions.
    • Failure: Ensure that errors (e.g., invalid item configurations) are handled gracefully, with clear feedback provided to the user.

This process will ensure that the reimplemented Item hierarchy meets quality standards for functionality, usability, and reliability.

Outcomes and overview

This document summarizes enhancements to the question module, including responsive UI updates, backend refactoring, and expanded test coverage. We implemented JSON-based responses across question types, streamlining data handling and improving performance. Comprehensive testing ensures system reliability and maintainability, laying a strong foundation for future updates and a cohesive user experience.

Team

  • Mentors
    • Prof. Edward F. Gehringer
    • Nainisha Bhallamudi
  • Members
    • Anchal Kakadia
    • Prerak Bhandari
    • Vihar Shah


References

  • Expertiza[2]
  • Previous team repository[3]
  • Active Record Migrations[4]
  • Migrating changes made on model[5]
  • Layouts and Rendering in Rails[6]
  • RSpec Testing[7]


Links

  • Project Board[8]
  • GitHub repo[9]
  • Link to initial pull request[10]
  • Video Link [11]