CSC/ECE 517 Spring 2024 - E2415. Reimplement responses controller.rb (Design Document)

From Expertiza_Wiki
Jump to navigation Jump to search

CSC/ECE 517 Spring 2024 - E2415: Reimplementation of responses_controller.rb (Design Document)

Expertiza

The Expertiza project, an open-source endeavor rooted in Ruby on Rails, embarks on continuous improvement to adapt and integrate modern software engineering practices. The Responses Controller is engineered to assist reviewers in submitting structured data that is specifically aligned with an assignment's rubrics, ensuring the provision of relevant questions for each round within the correct due date period. It enables a reviewer to evaluate and score the rubric questions pertinent to the assignment's topics. Furthermore, it ensures the delivery of appropriate questions for each assignment round, allowing reviewers to create and modify scores and comments for each of the rubric questions associated with the assignment. After reviewers submit their scored questions and comments, the Responses Controller dispatches an email notification to the instructor and the reviewed team's members.

Problem Statement

The ResponseController in Expertiza, a legacy system with conventions predating Rails standards, is overly complex, encompassing functionalities beyond basic CRUD operations and needing adherence to modern Rails naming and design principles. Key issues include the direct implementation of functionalities like sorting reviews and checking reviewer roles within the controller, suggesting a shift towards polymorphism and a more structured approach to code organization. Furthermore, the controller's handling of email notifications and feedback mechanisms is inconsistent, indicating the necessity for a dedicated helper to streamline communication processes. The reimplementation effort must focus on simplifying the controller, adhering to Rails conventions, and improving code readability and maintainability by appropriately distributing responsibilities.

Design Goal

The redesign of the `responses_controller.rb` is guided by several key objectives to improve the code quality, system behavior, and developer interaction. The goals include:

  • Maintainability and Scalability: Ensuring the code is easy to understand, modify, and extend. The reimplementation should simplify future updates and feature additions.
  • Adherence to Rails Best Practices: Following Rails conventions for naming, structure, and coding practices to ensure code consistency and reliability.
  • DRY Principle: "Don't Repeat Yourself" - removing redundant code and logic to create a more efficient and error-resistant codebase.
  • Single Responsibility Principle: Restructuring the controller and associated models so that each class and method has one purpose and one purpose only, leading to easier testing and management.
  • Improved Testing and Coverage: Enhancing test suites to cover more scenarios and edge cases, increasing confidence in the application's stability and performance.
  • Performance Optimization: Identifying and optimizing slow or inefficient areas in the code to ensure the application runs smoothly.
  • Clean Up Dead Methods: Audit the codebase for any unused ("dead") methods within the current controller and remove them to declutter the code.
  • Reduced Controller Complexity: We already have streamline the `ResponseController` to focus primarily on CRUD operations and extract non-essential logic to appropriate models or helpers, now we aim to implement the rest operations.

By meeting these design goals, the project aims to produce a `responses_controller.rb` that is robust, efficient, and a pleasure to work with, both for the current development team and for those who will maintain the system in the future.

Design Pattern

During the code refactoring process, we conscientiously followed various design patterns to enhance the overall structure. When refactoring the Response model and associated controller and helper methods in the application, several key design patterns and principles were followed to ensure improved code quality, maintainability, and scalability. Here are the primary patterns and principles that were considered:

Single Responsibility Principle (SRP)

This principle was applied to break down complex methods into smaller, more focused functions that handle a specific part of the process

  • In the Response Model:

Validate_params was broken down into multiple smaller methods, each handling a specific part of the validation process. This allows each method to manage one aspect of the validation, making the code easier to maintain and modify. Creation and management of relationships and basic attributes were clearly defined, ensuring that the Response class isn't overloaded with logic that doesn't pertain to its direct attributes or relationships.

  • In the ResponsesController:

The controller methods like create, update, show, etc., were defined to handle only HTTP requests and delegate business logic to the model or helper methods. This keeps the controller actions clean and focused on routing and basic request handling.

  • In the ResponseHelper:

Methods such as create_answers and update_answers are good examples where each method is tasked with either creating or updating answers but not both. This follows SRP by dividing the responsibilities into more manageable, discrete operations.

Factory Method

The Factory Method pattern can be seen implicitly where object creation processes are encapsulated within the model or helper methods, such as creating a new ResponseMap or generating new Answer objects. This ensures that object creation is modular and separated from the main application logic.

Strategy Pattern

By defining a family of algorithms (in this case, validation rules for different actions like create or update), encapsulating each one, and making them interchangeable, the strategy pattern lets the algorithm vary independently from the clients that use it. For instance, separating the validation conditions for creating and updating responses allows for flexible swapping and extension of validation logic without modifying the controller or model directly.

Observer Pattern

Used typically in scenarios where changes to a particular object need to notify other dependent objects automatically. In the context of this application, this could relate to notifying instructors or peers upon the submission or update of responses, handled through the helper methods for sending emails.

Template Method

This pattern can be used in defining the skeleton of an operation in a method, deferring some steps to subclasses or other methods. It's seen in how validate_params uses a general structure for validation but defers the specifics to methods like validate_create_conditions and validate_update_conditions.


By integrating these design patterns and principles, the refactoring aims to achieve a more robust, maintainable, and scalable system. This approach not only addresses current complexities but also lays a foundation for easier future enhancements and modifications.

Class Diagram

Use cases


Solutions/Details of Changes Made

Response Model

Methods within the response model were refactored or introduced, including:

set_content

Redesigned to gather and prepare the required data for response objects, optimizing the interaction with associated models

validate_params

This is the original method that was 46 lines long:

This method was significantly refactored to improve parameter validation. It was split into multiple smaller, focused methods, each dedicated to handling a specific aspect of the validation process. Each new method does one thing only, which makes them easier to understand and maintain.

  • assign_map_id_from_params: Sets the map_id for the response based on the provided parameters, ensuring the correct map ID is used for both creating and updating responses.

  • set_and_validate_response_map: Establishes and validates the presence of the response_map based on map_id. It's crucial to ensure that any response being created or updated is linked to a valid response map.This method attempts to find a ResponseMap based on map_id. If it fails to find one, it records an error and halts further validation, signaling an issue early in the process.

  • set_response_attributes(params):Assigns additional attributes to the response object from the parameters. This centralizes attribute setting, reducing redundancy and errors.Directly extracts values like round, version_num, additional_comment, and visibility from the parameters and assigns them to the response object.

  • action_specific_validation(params, action): Directs the validation flow based on whether the action is to create or update a response, organizing the logic clearly and preventing condition sprawl in the main validation method.Calls specific validation methods based on the action type: validate_create_conditions for creation and validate_update_conditions for updates.

  • validate_create_conditions: Ensures that a new response doesn't duplicate an existing one under the same response map, round, and version number.Searches for an existing response that matches the current map_id, round, and version_num. If such a response exists, it adds a validation error and prevents the creation of a duplicate response.

  • validate_update_conditions(params): Ensures that updates to a response are valid, specifically checking that a response isn't already submitted and that its map_id remains unchanged.Checks the submission status and whether there's an attempt to change the map_id. If either condition is violated, it records an error.

  • validate_submission_status(params): Updates the submission status of the response during the update process, ensuring the attribute is correctly set based on the provided parameters.Extracts and sets the is_submitted status from the parameters, which is crucial for controlling the editability of the response.

serialize_response

Improved to efficiently serialize response data for API interactions, enhancing the clarity and usability of data exchanges.

Response Controller

The ResponseController, originally extensive with numerous functions beyond basic CRUD operations, has been streamlined for our API application. In this context, there's no need to manage data variables for view pages, simplifying the handling of request data solely through request methods.To enhance the architecture and efficiency of our application, we've eliminated redundant methods and consolidated functionalities across the model, controller, and helper files. This restructuring was essential for refining the response endpoints specifically tailored for an API application.

Before we added Basic CRUD like New, Create, Update, edit, destroy.

Removed Methods: Legacy methods like Questionnaire_from_response_map and Questionnaire_from_response were removed following the refactoring of set_content, which now handles its functionalities internally without the need for these methods.

Show_calibration_results_for_student

Before:

The old implementation also made use of database queries in the view. This will not be possible in the reimplemented Expertiza, and the required data will need to be made available in the JSON response sent by the controller.

The new show_calibration_results_for_student method retrieves and displays calibration and review responses based on provided map IDs. It fetches responses using these IDs, retrieves associated questions and answers, and returns the data as a formatted JSON object. If a response is not found, it returns an error indicating the missing response. The method handles any exceptions by returning a standard error message, ensuring robust error handling throughout the process. Serves as an API endpoint to fetch detailed response data for a student's calibration and review tasks, providing all necessary details about the questions asked and the answers provided in both contexts


Response Helper

The method create_update_answers(response, answers) was originally handling both the creation and updating of answer records within a single method:

To improve code maintainability and adhere to the Single Responsibility Principle, this method has been divided into two distinct methods:

Create_answers

This method focuses solely on creating new answer records. It iterates over the answers provided, checking if each answer does not already exist in the database. If the answer does not exist, it creates a new record for that answer. This ensures that each answer is unique and prevents duplication.

Update_answers

This method is responsible for updating existing answer records. It searches for existing answers in the database based on the response and question identifiers. If an answer is found, it updates the existing record with the new information provided. This method ensures that all modifications to answers are captured accurately and that the database is kept up-to-date.

Files Modified/Added

List of primary files modified or created includes:

  • responses_controller.rb
  • response_helper.rb
  • response.rb


Test

Validate Parameters

Postman Tests

Separated Answer Creation and Update Logic

Postman Tests

Creation:

Update:

Team

Mentor
  • Ameya Vaichalkar
Members
  • Jeff Riehle
  • Maday Moya
  • Shardul Ladekar

Links

Postman Video Links:

Pull request: https://github.com/expertiza/reimplementation-back-end/pull/92

Model Tests Video: https://youtu.be/7x8x4l3AksE

Controller Tests Video: https://youtu.be/0PV-ycXfyZU

References