User:Bkurra
CSC/ECE 517 Spring 2024 - E2415: Reimplementation of responses_controller.rb (Design Document)
Expertiza
The Expertiza project, an open-source initiative based on Ruby on Rails, pursues ongoing enhancement to incorporate contemporary software engineering methodologies. The Responses Controller is designed to aid reviewers in supplying organized data that conforms to an assignment's rubrics, assuring the availability of pertinent questions for each round within the appropriate deadline. It allows a reviewer to assess and grade the rubric questions relevant to the assignment's subjects. Moreover, it guarantees the provision of relevant questions for each assignment round, enabling reviewers to generate and adjust scores and remarks for each rubric question linked to the assignment. Upon the submission of scored questions and comments by reviewers, the Responses Controller sends an email message to the instructor and the members of the reviewed team.
Problem Statement
The ResponseController in Expertiza, a historical system with conventions that predate Rails standards, is too intricate, incorporating functionalities that extend beyond simple CRUD operations and requiring compliance with contemporary Rails nomenclature and design concepts. Critical concerns encompass the direct execution of functions such as sorting reviews and verifying reviewer roles within the controller, indicating a transition towards polymorphism and a more systematic method of code organization. Moreover, the controller's management of email notifications and feedback systems is erratic, highlighting the need for a specialized assistant to optimize communication procedures. The reimplementation initiative must concentrate on streamlining the controller, conforming to Rails principles, and enhancing code readability and maintainability through the judicious allocation of responsibilities.
Design Goal
The redesign of `responses_controller.rb` is driven by several primary aims aimed at enhancing code quality, system performance, and developer engagement. The objectives encompass:
- Maintainability and Scalability: Guaranteeing the code is comprehensible, modifiable, and extensible. The reimplementation should facilitate future updates and the incorporation of new features.
- Compliance with Rails Best Practices: Adhering to Rails conventions on nomenclature, architecture, and coding methodologies to guarantee code uniformity and dependability.
- DRY Principle: "Don't Repeat Yourself" - eliminating unnecessary code and logic to enhance efficiency and reduce errors in the codebase.
- Single Responsibility Principle: Reorganizing the controller and related models to ensure that each class and method has a singular purpose, hence facilitating enhanced testing and management.
- Enhanced Testing and Coverage: Augmenting test suites to encompass a broader range of scenarios and edge situations, hence bolstering confidence in the application's stability and performance.
- Performance Optimization: Recognizing and enhancing sluggish or ineffective segments in the code to guarantee the application operates seamlessly.
- Eliminate Obsolete Methods: Conduct an audit of the codebase to identify and delete any unneeded ("dead") methods inside the present controller to streamline the code.
- Diminished Controller Complexity: We have already streamlined the `ResponseController` to concentrate mostly on CRUD activities and have extracted non-essential functionality to suitable models or helpers; now we intend to implement the remaining operations.
By achieving these design objectives, the project seeks to create a `responses_controller.rb` that is resilient, efficient, and user-friendly for both the current development team and future system maintainers.
Design Pattern
Throughout the code rewriting effort, we meticulously adhered to certain design patterns to improve the overall architecture. During the redesign of the Response model and its corresponding controller and helper methods within the application, several fundamental design patterns and concepts were adhered to in order to enhance code quality, maintainability, and scalability. The following are the principal patterns and principles that were taken into account:
Single Responsibility Principle (SRP)
This technique was utilized to decompose intricate methods into smaller, more targeted functions that manage a specific aspect of the process.
In the Response Model, Validate_params was subdivided into several smaller methods, each responsible for a distinct aspect of the validation process. This enables each method to oversee a specific facet of the validation, hence enhancing the maintainability and modifiability of the code. The establishment and administration of relationships and fundamental properties were distinctly articulated, ensuring that the Response class remains unencumbered by logic unrelated to its specific attributes or relationships.
In the ResponsesController, the methods such as create, update, and show are designed solely to manage HTTP requests while delegating business logic to the model or helper methods. This maintains the controller actions in a clean and focused manner for routing and fundamental request management.
In the ResponseHelper, methods like create_answers and update_answers exemplify the principle that each method is designated for either the creation or the updating of answers, but not both. This adheres to SRP by partitioning duties into more manageable, distinct operations.
Factory Method
The Factory Method design is implicitly evident when object generation procedures are encapsulated within the model or auxiliary methods, such as instantiating a new ResponseMap or generating new Answer objects. This guarantees that object instantiation is modular and distinct from the primary application logic.
Strategy Pattern
The strategy design enables the independent variation of algorithms by establishing a family of encapsulated algorithms, such as validation criteria for activities like creation or updating, and allowing them to be interchangeable for the clients that utilize them. Separating the validation criteria for response creation and updating facilitates the flexible interchange and enhancement of validation logic without necessitating direct alterations to the controller or model. Observer Pattern Typically employed in situations where modifications to a certain object must automatically inform other dependant objects. Within the framework of this program, this may pertain to alerting instructors or peers following the submission or modification of responses, managed via the auxiliary ways for dispatching emails.
Template Method
This pattern can be employed to delineate the framework of an operation within a method, postponing certain phases to subclasses or other methods. The validation process in validate_params employs a generic framework while delegating specific details to methods such as validate_create_conditions and validate_update_conditions.
The refactoring seeks to establish a more resilient, manageable, and scalable system through the integration of various design patterns and concepts. This method not only resolves existing complexities but also establishes a basis for more straightforward future improvements and alterations.
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
Team
Mentor
- Richard Li
Members
- Loyda Yusufova
- Bhuvan Chandra Kurra
Links
Postman Video Links:
- create: https://youtu.be/hXQl-JkfuUc
- update: https://youtu.be/BeifLsCRQlk
- show_calibration_results_for_student: https://www.youtube.com/watch?v=ltJarFGb25k
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