Skip to content

Case Study: Enhancing Code with comments and documentation using genAI

Yureshwar Ravuri edited this page Jun 27, 2025 · 3 revisions

Case Study: Enhancing the Aadhaar OTP function with comments and documentation

Introduction

In this case study, we will examine the process of refactoring and improving a Ruby code snippet responsible for generating a One-Time Password (OTP) for the Aadhaar verification process. The original code lacked proper documentation, had inconsistent variable naming, and lacked modularity. The goal was to enhance the code's maintainability, readability, and security while preserving its functionality.

Problem Statement

The existing code for generating Aadhaar OTP had the following issues:

  • Lack of proper documentation and comments
  • Inconsistent variable naming conventions
  • Poor code organization and modularity
  • Limited error handling and logging

These issues made it difficult for developers to understand, maintain, and extend the codebase, potentially leading to errors and security vulnerabilities.

Solution Approach

To address the identified issues, the following steps were taken:

  1. Code Documentation:

    • YARD-style comments were added to document the purpose and functionality of the code.
    • Each method parameter and return value were clearly described.
    • Inline comments were added to explain complex or critical sections of the code.
  2. Code Refactoring:

    • The code was restructured to improve organization and modularity.
    • Logical sections were separated with clear boundaries and consistent indentation.
    • Variable names were updated to follow Ruby naming conventions and enhance readability.
  3. Error Handling and Logging:

    • Detailed error messages were added to provide more information about specific error scenarios.
    • Additional logging statements were included to capture relevant details for debugging and troubleshooting.
    • The code field was added to error responses to indicate the specific HTTP status code.

Results and Benefits

The refactored code achieved the following benefits:

  1. Improved Maintainability:

    • The code is now well-documented, making it easier for developers to understand and maintain.
    • The modular structure allows for easier updates and modifications in the future.
  2. Enhanced Readability:

    • Consistent variable naming and code organization improve code readability.
    • YARD-style comments provide clear documentation for developers, reducing the likelihood of misinterpretation or errors.
  3. Better Error Handling:

    • Detailed error messages and comprehensive logging facilitate debugging and troubleshooting.
    • The inclusion of the code field in error responses provides more granular information for error handling.
  4. Strengthened Security:

    • Input validation and encryption mechanisms ensure the security of sensitive Aadhaar data.
    • Proper authentication token validation prevents unauthorized access to the ABHA service.

Conclusion

The above was achieved with less than 20 mins of genAI collaboration. We achieved significant improvements in maintainability, readability, error handling, and security. The code is now more modular, well-documented, and easier to understand and extend. The added security measures protect sensitive Aadhaar data and ensure secure communication with the ABHA service.

Prompt that can be used for Documentation & Comments

Assume the role of a senior software architect specializing in Node.js and JavaScript. Analyze the provided code, which has already been refined for error handling, input validation, sanitization, type strictness, and security enhancements. Your sole task is to improve its documentation and inline comments without modifying any functionality.

Ensure that every function, parameter, return value, and complex logic is well-documented using clear and structured comments. Add inline comments for all conditions, including edge cases, error-handling logic, security measures, and validation checks, ensuring that every decision point is explicitly explained. Maintain consistency in documentation format, adhering to best practices such as JSDoc-style comments where applicable.

Strictly avoid altering existing logic, optimizing performance, or making security-related modifications. Focus only on enhancing clarity through documentation.

Provide a detailed report summarizing the added documentation and inline comments. At the end of the analysis, present the fully documented code with all inline comments incorporated in a structured final output, ensuring completeness and ease of understanding.

Appendix

'Before genAI documentation' file

Can be found here

The 'After genAI documentation' file is below.

    # Generates OTP for Aadhaar verification process
    # @param [String] aadhar The 12-digit Aadhaar number
    # @return [Hash] Response containing status and relevant messages
    def generate_aadhar_otp
      begin
        # Initial validation for Aadhaar presence
        sanitized_aadhaar = Sanitize.fragment(params["aadhar"].to_s)
                             .gsub(/[^0-9]/, '')
                             .strip

        # Initial presence check
        unless sanitized_aadhaar.present?
          return @response = { 
            status: "error", 
            message: "Aadhaar number is required"
          }
        end

        # Length and format validation
        unless sanitized_aadhaar.length == AADHAAR_LENGTH && 
              sanitized_aadhaar.match?(AADHAAR_REGEX)
          return @response = {
            status: "error",
            message: "Invalid Aadhaar format. Please provide a valid 12-digit Aadhaar number."
          }
        end
        
        # Validate Aadhaar number format using Verhoeff algorithm
        unless VerhoeffValidator.validate_aadhaar(sanitized_aadhaar)
          return @response = { 
            status: "error", 
            message: "Invalid Aadhaar number. Please provide a valid 12-digit Aadhaar number."
          }
        end

        # Encrypt Aadhaar number using RSA OAEP padding
        encrypted_aadhar = RsaEncryption.oaep_mgf1_padding(sanitized_aadhaar)
        
        # Call ABHA service to generate OTP
        otp_response = AbhaWebService.generate_aadhar_otp(encrypted_aadhar)
        
        # Validate response structure
        unless otp_response.is_a?(Hash) && otp_response[:resp_status].present?
          raise StandardError, "Invalid response format from ABHA service"
        end

        # Handle different response status codes
        case otp_response[:resp_status]
        when "200"
          # Successful OTP generation
          @otp_txn_id = JSON.parse(otp_response[:resp_body])["txnId"]
          raise StandardError, "Transaction ID missing in response" if @otp_txn_id.nil?
          @response = { status: "success", txn_id: @otp_txn_id }
        
        when "400"
          # Bad request handling
          Rails.logger.error("Bad Request: #{otp_response[:resp_body]}")
          @response = { 
            status: "error", 
            code: 400,
            message: "Invalid request parameters", 
            error: otp_response[:resp_body] 
          }
        
        when "401"
          # Authentication failure
          Rails.logger.error("Unauthorized: #{otp_response[:resp_body]}")
          @response = { 
            status: "error",
            code: 401, 
            message: "Authentication failed", 
            error: otp_response[:resp_body] 
          }
        
        when "404"
          # Resource not found
          Rails.logger.error("Not Found: #{otp_response[:resp_body]}")
          @response = { 
            status: "error",
            code: 404, 
            message: "Resource not found", 
            error: otp_response[:resp_body] 
          }
        
        when "429"
          # Rate limiting response
          Rails.logger.error("Rate Limited: #{otp_response[:resp_body]}")
          @response = { 
            status: "error",
            code: 429, 
            message: "Too many requests, please try again later", 
            error: otp_response[:resp_body] 
          }
        
        when "500"
          # Server error handling
          Rails.logger.error("ABHA Service Error: #{otp_response[:resp_body]}")
          @response = { 
            status: "error",
            code: 500, 
            message: "ABHA service is currently unavailable", 
            error: otp_response[:resp_body] 
          }
        
        else
          # Unexpected response handling
          Rails.logger.error("Unexpected Response: #{otp_response[:resp_body]}")
          @response = { 
            status: "error",
            code: 422, 
            message: "Unexpected response from ABHA service", 
            error: otp_response[:resp_body] 
          }
        end

      rescue JSON::ParserError => e
        # Handle JSON parsing errors
        Rails.logger.error("JSON parsing error: #{e.message}")
        @response = { 
          status: "error",
          code: 500, 
          message: "Invalid response format",
          error: e.message 
        }
        
      rescue StandardError => e
        # Generic error handling with detailed logging
        Rails.logger.error("Error generating Aadhar OTP: #{e.message}")
        Rails.logger.error(e.backtrace.join("\n"))
        @response = { 
          status: "error",
          code: 500, 
          message: "Something went wrong",
          error: e.message 
        }
      end
    end

Clone this wiki locally