CSC/ECE 517 Fall 2023 - E2375. Refactor classes relating to signing up for topics

From Expertiza_Wiki
Jump to navigation Jump to search

Introduction

  • When managing sign-ups within expertiza, the evolution of functionality often leads to a need for refactoring existing code. In this case, several classes— sign_up_sheet.rb, sign_up_topic.rb, and signed_up_team.rb —require restructuring to streamline their functionalities and ensure they align with the current project landscape.
  • This refactoring endeavor aims to declutter, reorganize, and enhance code readability and maintainability by removing redundant functionalities and repositioning methods in classes where they serve their intended purposes more explicitly. The end goal is a more coherent and efficient codebase that reflects the current needs of the project while laying the groundwork for future enhancements.

Methods to be refactored

  • There's a need for a thorough reevaluation and reorganization of the methods within the classes related to signing up for topics. Let's break down the key observations and areas requiring attention in each class:

Sign Up Sheet

  • Methods like signup_team, confirmTopic, create_SignUpTeam, and slotAvailable? lack clear indication of their purpose or follow confusing naming conventions.

Signup Topic

  • Methods like find_slots_filled, find_slots_waitlisted, and slotAvailable? lack clarity in their purpose or could be misleading.

Signed Up Team

  • Methods like find_team_participants could be named more intuitively, while others like topic_id suggest a Law of Demeter violation.

Overview

  • Many methods lack clear and descriptive names, making it challenging to discern their purpose without diving into their implementation.
  • There are instances of redundant functionalities and methods reimplemented in different classes, indicating potential code consolidation opportunities.
  • Reassigning methods to classes where they logically belong and adhering to encapsulation principles could significantly enhance code readability and maintainability.

To improve these classes, a systematic approach to renaming, reassigning, and potentially consolidating methods could streamline functionality, improve code readability, and adhere more closely to object-oriented design principles. Refactoring should focus on clearer method naming, reducing redundancy, adhering to encapsulation, and promoting better organization within the codebase.

Design in sign_up_sheet.rb file

(1) self.signup_team

Existing code:

 def self.signup_team(assignment_id, user_id, topic_id = nil)
    users_team = SignedUpTeam.find_team_users(assignment_id, user_id)
    if users_team.empty?
      # if team is not yet created, create new team.
      # create Team and TeamNode
      team = AssignmentTeam.create_team_with_users(assignment_id, [user_id])
      # create SignedUpTeam
      confirmationStatus = SignUpSheet.confirmTopic(user_id, team.id, topic_id, assignment_id) if topic_id
    else
      confirmationStatus = SignUpSheet.confirmTopic(user_id, users_team[0].t_id, topic_id, assignment_id) if topic_id
    end
    ExpertizaLogger.info "The signup topic save status:#{confirmationStatus} for assignment #{assignment_id} by #{user_id}"
    confirmationStatus
  end

Code smells:

  • Conditional Complexity: There's conditional complexity within the method based on whether users_team is empty or not, leading to slightly repetitive code.
  • Lack of Clear Separation of Concerns: The method handles team creation, sign-up confirmation, and logging within the same block, which might violate the single responsibility principle.
  • Magic Numbers/Variables: users_team[0].t_id uses index 0 directly, assuming there's always at least one entry in users_team.
  • Change method name to Signup_sheet.

What to improve

  • Error Handling: Add error handling for potential failures during team creation or sign-up processes.

(2) self.confirmTopic

Existing Code:

 def self.confirmTopic(user_id, team_id, topic_id, assignment_id)
    # check whether user has signed up already
    user_signup = SignUpSheet.otherConfirmedTopicforUser(assignment_id, team_id)
    users_team = SignedUpTeam.find_team_users(assignment_id, user_id)
    team = Team.find(users_team.first.t_id)
    if SignedUpTeam.where(team_id: team.id, topic_id: topic_id).any?
      return false
    end

    sign_up = SignedUpTeam.new
    sign_up.topic_id = topic_id
    sign_up.team_id = team_id
    result = false
    if user_signup.empty?

      # Using a DB transaction to ensure atomic inserts
      ApplicationRecord.transaction do
        # check whether slots exist (params[:id] = topic_id) or has the user selected another topic
        team_id, topic_id = create_SignUpTeam(assignment_id, sign_up, topic_id, user_id)
        result = true if sign_up.save
      end
    else
      # This line of code checks if the "user_signup_topic" is on the waitlist. If it is not on the waitlist, then the code returns 
      # false. If it is on the waitlist, the code continues to execute.
      user_signup.each do |user_signup_topic|
        return false unless user_signup_topic.is_waitlisted
      end

      # Using a DB transaction to ensure atomic inserts
      ApplicationRecord.transaction do
        # check whether user is clicking on a topic which is not going to place him in the waitlist
        result = sign_up_wailisted(assignment_id, sign_up, team_id, topic_id)
      end
    end

    result
  end

Code smells:

  • Method Length: The method is quite lengthy and performs multiple actions. It might benefit from breaking down into smaller, more focused methods.
  • Complex Conditional Flow: The conditional flow involving transactions and multiple conditions could be challenging to follow and understand at first glance.

Design Considerations:

  • Separation of Concerns: Ensure clear separation of concerns within the method. Each section of code should handle a specific aspect of the logic.

Refactoring and Code Enhancements:

  • Extract Conditional Blocks into Methods: Break down conditional blocks into smaller methods to improve readability and maintainability. For instance, separate logic for handling cases where the user has already signed up or is on the waitlist.
  • Improve Variable Naming: Use more descriptive variable names for better readability and understanding of the code. For example, renaming result, sign_up, user_signup, and user_signup_topic to more descriptive names would enhance clarity.

(3) self.create_SignUpTeam

Existing Code:

 def self.create_SignUpTeam(assignment_id, sign_up, topic_id, user_id)
    if slotAvailable?(topic_id)
      sign_up.is_waitlisted = false
      # Create new record in signed_up_teams table
      team_id = TeamsUser.team_id(assignment_id, user_id)
      topic_id = SignedUpTeam.topic_id(assignment_id, user_id)
      SignedUpTeam.create(topic_id: topic_id, team_id: team_id, is_waitlisted: 0, preference_priority_number: nil)
      ExpertizaLogger.info LoggerMessage.new('SignUpSheet', user_id, "Sign up sheet created with teamId #{team_id}")
    else
      sign_up.is_waitlisted = true
    end
    [team_id, topic_id]
  end

Issues in the above method

  • Naming Convention: The method name create_SignUpTeam should follow Ruby's naming convention, which typically uses snake_case for method names. Renaming it to create_sign_up_team would align better with Ruby conventions.
  • Variable Ambiguity: The method uses topic_id and team_id as both method parameters and local variables. Reassigning these variables inside the method can cause confusion and may lead to unexpected behavior. It's advisable to use different variable names to avoid ambiguity.

Suggestions for Improvement:

  • Refactor for Clarity: Separate the logic for creating sign-up sheets and managing waitlist status into distinct methods to improve readability and maintainability.
  • Variable Naming: Use more descriptive variable names to improve clarity and avoid reassigning values to parameters.
  • Use Constants: Replace hardcoded values like 0 and nil with constants or meaningful representations for better code readability.

Issues with the Return Statement:

  • Lack of Clarity: The return statement doesn't explicitly communicate the method's primary purpose or what the caller should do with the returned values. It returns two values without context, which might lead to ambiguity.
  • Mixed Responsibilities: The method's primary responsibility seems to be creating a sign-up team or managing waitlist status. Returning [team_id, topic_id] might not be directly related to these actions and could confuse the caller about the returned values' significance.

Suggestions for Improvement:

  • Use Struct or Hash: Instead of returning an array of values without context, consider using a Ruby Struct or a Hash to encapsulate the return values. This way, the returned data can be labeled with descriptive keys, providing better context to the caller.
  • Example using a Struct:
SignUpResult = Struct.new(:team_id, :topic_id)
return SignUpResult.new(team_id, topic_id)

(4) self.slotAvailable?

Existing Code:

def self.slotAvailable?(topic_id)
    SignUpTopic.slotAvailable?(topic_id)
end

Issues:

  • Code Duplication: By redefining the slotAvailable? method in the current file when it already exists in another file, the code introduces unnecessary duplication. This leads to maintenance issues as any changes to the logic or behavior of this method need to be updated in both places, which can be error-prone and time-consuming.
  • Violation of DRY Principle: The "Don't Repeat Yourself" (DRY) principle suggests that code should have a single, unambiguous representation within a system. Redefining the same method in different places violates this principle, potentially causing inconsistencies and confusion.

Design in sign_up_topic.rb file

(1) self.find_slots_filled

Existing Code:

def self.find_slots_filled(assignment_id)
    # SignUpTopic.find_by_sql("SELECT topic_id as topic_id, COUNT(t.max_choosers) as count      FROM sign_up_topics t JOIN signed_up_teams u ON t.id = u.topic_id WHERE t.assignment_id =" + assignment_id+  " and u.is_waitlisted = false GROUP BY t.id")
    SignUpTopic.find_by_sql(['SELECT topic_id as topic_id, COUNT(t.max_choosers) as count FROM sign_up_topics t JOIN signed_up_teams u ON t.id = u.topic_id WHERE t.assignment_id = ? and u.is_waitlisted = false GROUP BY t.id', assignment_id])
end

Problems Identified:

  • SQL Query Within the Method: The method contains a SQL query directly embedded in the code. Embedding SQL queries like this can make the code less maintainable and harder to understand, especially for developers who might not be familiar with SQL or the database schema.
  • Complex SQL Logic: The SQL query combines multiple tables (sign_up_topics and signed_up_teams) and performs aggregations (COUNT) and joins based on certain conditions (is_waitlisted = false). Such complexity in the query can make it challenging to troubleshoot or modify in the future.

Suggestions for Improvement:

  • Separation of Concerns: Extract the SQL query into a separate method or a query builder class to abstract away the SQL complexities from the method. This separation helps in better code organization and maintainability.
  • Encapsulate SQL Logic: Abstract the SQL logic into a method that accepts necessary parameters, allowing better reusability across different parts of the application without duplicating code.

(2) self.find_slots_waitlisted

Existing Code:

def self.find_slots_waitlisted(assignment_id)
    # SignUpTopic.find_by_sql("SELECT topic_id as topic_id, COUNT(t.max_choosers) as count FROM sign_up_topics t JOIN signed_up_teams u ON t.id = u.topic_id WHERE t.assignment_id =" + assignment_id +  " and u.is_waitlisted = true GROUP BY t.id")
    SignUpTopic.find_by_sql(['SELECT topic_id as topic_id, COUNT(t.max_choosers) as count FROM sign_up_topics t JOIN signed_up_teams u ON t.id = u.topic_id WHERE t.assignment_id = ? and u.is_waitlisted = true GROUP BY t.id', assignment_id])
  End

Identified Issues:

  • SQL Query Embedded in Code: Similar to the previous method, this method contains a SQL query embedded directly within the code. This can lead to reduced maintainability and readability, especially for developers unfamiliar with the SQL logic or database schema.
  • Complex SQL Logic: The SQL query combines tables (sign_up_topics and signed_up_teams), performs aggregations (COUNT), and includes conditional logic (is_waitlisted = true). This level of complexity in the query might hinder code readability, debugging, and future modifications.

Suggestions for Improvement:

  • Separation of Concerns: Extract the SQL query logic into a separate method or a query builder class to separate it from the method. This separation aids in better code organization and maintainability.
  • Encapsulation of SQL Logic: Abstract the SQL logic into a method that accepts necessary parameters, facilitating better reuse across different sections of the application without repeating the code.

(3) self.slotAvailable?

Existing Code:

def self.slotAvailable?(topic_id)
    topic = SignUpTopic.find(topic_id)
    no_of_students_who_selected_the_topic = SignedUpTeam.where(topic_id: topic_id, is_waitlisted: false)

    if no_of_students_who_selected_the_topic.nil?
      return true
    else
      if topic.max_choosers > no_of_students_who_selected_the_topic.size
        return true
      else
        return false
      end
    end
  end

Issues Identified:

  • Instance vs. Class Method: This method could potentially be more appropriate as an instance method rather than a class method. It appears to operate on an instance of a topic (SignUpTopic), accessing specific data related to a topic instance. Refactoring it as an instance method might improve the code's readability and alignment with object-oriented principles.
  • Handling of no_of_students_who_selected_the_topic: The method checks if no_of_students_who_selected_the_topic is nil. However, the where method of ActiveRecord returns an empty ActiveRecord::Relation if no records match the query, never returning nil. Therefore, the condition if no_of_students_who_selected_the_topic.nil? will not be executed.

Suggestions for Improvement:

  • Refactoring to Instance Method: If this method indeed pertains to a specific instance of SignUpTopic, refactor it into an instance method. This way, it can directly operate on a specific topic instance.
  • Handle no_of_students_who_selected_the_topic Appropriately: Since no_of_students_who_selected_the_topic will never be nil, adjust the condition to handle an empty collection or use empty? to check if it's empty.

Design in signed_up_team.rb file

(1) self.find_team_participants

Existing Code:

def self.find_team_participants(assignment_id, ip_address = nil)
    @participants = SignedUpTeam.joins('INNER JOIN sign_up_topics ON signed_up_teams.topic_id = sign_up_topics.id')
                                .select('signed_up_teams.id as id, sign_up_topics.id as topic_id, sign_up_topics.topic_name as name,
                                  sign_up_topics.topic_name as team_name_placeholder, sign_up_topics.topic_name as user_name_placeholder,
                                  signed_up_teams.is_waitlisted as is_waitlisted, signed_up_teams.team_id as team_id')
                                .where('sign_up_topics.assignment_id = ?', assignment_id)
    @participants.each_with_index do |participant, i|
      participant_names = User.joins('INNER JOIN teams_users ON users.id = teams_users.user_id')
                              .joins('INNER JOIN teams ON teams.id = teams_users.team_id')
                              .select('users.name as u_name, teams.name as team_name')
                              .where('teams.id = ?', participant.team_id)

      team_name_added = false
      names = '(missing team)'

      participant_names.each do |participant_name|
        if team_name_added
          names += User.find_by(name: participant_name.u_name).name(ip_address) + ' '
          participant.user_name_placeholder += User.find_by(name: participant_name.u_name).name(ip_address) + ' '
        else
          names = '[' + participant_name.team_name + '] ' + User.find_by(name: participant_name.u_name).name(ip_address) + ' '
          participant.team_name_placeholder = participant_name.team_name
          participant.user_name_placeholder = User.find_by(name: participant_name.u_name).name(ip_address) + ' '
          team_name_added = true
        end
      end
      @participants[i].name = names
    End

Problems Identified:

  • Naming Convention: Using an instance variable @participants suggests that this method is intended to populate a class instance variable. However, this method is a class method, and using instance variables within it can cause confusion. Renaming it to a local variable like participants would be more appropriate.
  • Redundant Database Queries: Within the iteration, there are multiple calls to the database (User.find_by(name: participant_name.u_name).name(ip_address)). These queries within loops can significantly impact performance, leading to potential N+1 query problems.

Suggestions for Improvement:

  • Use of Local Variable: Instead of using @participants, use a local variable participants within the scope of the method. This change clarifies that it's not intended to store data persistently in the class.
  • Reduce Database Queries in Loops: Retrieve necessary data beforehand and avoid querying the database multiple times within loops. Utilize data structures or caching mechanisms to store and reuse fetched data efficiently.

(2) self.topic_id

Existing Code:

def self.topic_id(assignment_id, user_id)
    # team_id variable represents the team_id for this user in this assignment
    team_id = TeamsUser.team_id(assignment_id, user_id)
    topic_id_by_team_id(team_id) if team_id
  End

Issues Identified:

  • LoD Violation: Indirect Access to Associated Model: The method TeamsUser.team_id(assignment_id, user_id) is accessed directly within topic_id, which in turn calls topic_id_by_team_id(team_id) if team_id is present. This pattern violates the Law of Demeter by reaching into the structure of associated models, potentially leading to tight coupling and decreased maintainability.

Suggestions for Improvement:

  • Encapsulation and Modularity: To adhere more closely to the Law of Demeter, consider encapsulating this logic within the appropriate model or service. This helps in keeping responsibilities more contained within their respective models or services, promoting modularity and separation of concerns.
  • Direct Association Usage: If available, utilize direct associations or relationships defined within the models to access related data more directly. This approach aligns better with the Law of Demeter by restricting access to a model's immediate relationships rather than reaching multiple levels down the association chain.

Conclusion

In conclusion, the outlined refactoring process presents a clear path towards substantial enhancements within the sign-up management classes of Expertiza. By addressing the identified issues—confusing method names, redundant functionalities, and violations of coding principles—we're poised to elevate the functionality and maintainability of these crucial components.

The proposed improvements, encompassing method renaming, separation of concerns, and adherence to coding conventions, signify a concerted effort to refine the codebase. These changes are not merely about tidying up the existing code; they are a strategic investment in the project's future.

Moving forward, we'll embark on a systematic approach to refactor these classes. Each step will involve precise modifications aimed at streamlining functionalities, reducing complexities, and aligning methods with their intended purposes. This iterative process will be driven by a commitment to best practices, readability, and scalability, ensuring that the codebase evolves in sync with the evolving needs of Expertiza.

Team

Mentor
  • Ed Gehringer
Members
  • Dinesh Pasupuleti <dpasupu@ncsu.edu>
  • Prateek Singamsetty <pksingam@ncsu.edu>
  • Rushabh Shah <rshah32@ncsu.edu>