Create Logos

Using AI to Document Your Code Like a Pro

Using AI to Document Your Code Like a Pro blog article main image

A GPT-Assisted Approach

Introduction

Using AI models like GPT to add comments to existing code can provide several advantages:

  1. Improving Code Understandability
    By adding descriptive comments to code, AI can make it easier for developers to understand the code's purpose and functionality, which is particularly useful when dealing with a large codebase or when onboarding new team members.
  2. Enhancing Code Maintainability
    With comprehensive and meaningful comments, code maintenance becomes easier. Developers can understand the logic behind the code without needing to decode each line, simplifying the process of modifying or updating code.
  3. Reducing Onboarding Time
    For developers new to a codebase, AI-generated comments can provide immediate insights into the workings of the code, reducing the time required to become productive.
  4. Automating Documentation
    In addition to inline code comments, AI could generate high-level documentation for code files or modules, further aiding understanding and maintenance.
  5. Time Savings
    Writing comments can be time-consuming. If an AI can accurately summarize what a piece of code is doing, it can save developers significant time, allowing them to focus more on coding itself.
  6. Bug Identification
    During the process of generating comments, the AI might identify sections of code that are ambiguous or potentially erroneous, helping to improve code quality.
  7. Standardizing Commenting Practices
    AI can enforce a consistent comment style across a codebase, making the code easier to read and understand.
  8. Promoting Good Coding Practices
    By providing comments, AI tools can help encourage developers to write more understandable and maintainable code, fostering best practices within development teams.

However, it's worth mentioning that the quality and accuracy of AI-generated comments depend heavily on the AI's training and capabilities. While AI can provide significant assistance, human oversight is crucial to ensure that the comments accurately reflect the code's intent and functionality.

In this post, we'll add documentation to our previously created TypeScript and Python user authentication libraries.

GPT Prompt

I want to take the following Typescript and Python authentication libraries and add documentation.
For Typescript, I would like the documentation to follow the format for the TypeDoc standard 
(see typedoc.org) and for the Python implementation I would like to follow the format for the 
Sphinx standard (see sphinx-doc.org)

Typescript:

import * as bcrypt from 'bcrypt';

class UserAuth {
  static validateEmail(email: string): boolean {
    let emailRegex = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z]{2,}$/;
    return emailRegex.test(email);
  }
  
  static validatePassword(password: string): boolean {
    let passwordRegex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{12,}$/;
    return passwordRegex.test(password);
  }

  static splitEmail(email: string): [string, string, string] {
    const [username, domain] = email.split('@');
    const domainParts = domain.split('.');
    const topLevelDomain = domainParts[domainParts.length - 1];

    return [username, domain, topLevelDomain];
  }
  
  static async hashPassword(password: string): Promise<string> {
    const salt = await bcrypt.genSalt(10);
    const hashedPassword = await bcrypt.hash(password, salt);
    return hashedPassword;
  }
  
  static async validateHash(password: string, hash: string): Promise<boolean> {
    return await bcrypt.compare(password, hash);
  }
}

Python:

import re
from typing import Tuple
from passlib.hash import bcrypt

class UserAuth:
  @staticmethod
  def validate_email(email: str) -> bool:
    email_regex = '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z]{2,}$'
    return bool(re.match(email_regex, email))
  
  @staticmethod
  def validate_password(password: str) -> bool:
    password_regex = '^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{12,}$'
    return bool(re.match(password_regex, password))
  
  @staticmethod
  def split_email(email: str) -> Tuple[str, str, str]:
    username, rest = email.split("@")
    domain_name, top_level_domain = rest.split(".")
    return username, rest, top_level_domain
  
  @staticmethod
  def hash_password(password: str) -> str:
    return bcrypt.using(rounds=12).hash(password)
  
  @staticmethod
  def validate_hash(password: str, hashed_password: str) -> bool:
    return bcrypt.verify(password, hashed_password)

Prompt Overview

In this case, the prompt for the AI was to add documentation to existing code libraries according to specific documentation standards.

The Typescript and Python code to be commented was provided in full.

With a detailed prompt, the AI can generate the most relevant and beneficial responses.

GPT Response

Let's start with our TypeScript code. Here is how we can document it following the TypeDoc standard:

import * as bcrypt from 'bcrypt';

/**
 * Class UserAuth 
 * @description This class contains methods for user authentication tasks.
 */
class UserAuth {

  /**
   * @function validateEmail
   * @param {string} email - The email address to be validated.
   * @description This method validates whether a given string is a valid email address.
   * @returns {boolean} - Returns true if the email is valid, false otherwise.
   */
  static validateEmail(email: string): boolean {
    let emailRegex = /^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z]{2,}$/;
    return emailRegex.test(email);
  }

  // ... Similar comments for other methods ...
}

Now, let's document the Python implementation using the Sphinx standard:

import re
from typing import Tuple
from passlib.hash import bcrypt

class UserAuth:
    """
    A class that contains methods for user authentication tasks.
    """

    @staticmethod
    def validate_email(email: str) -> bool:
        """
        Validates whether a given string is a valid email address.

        :param email: The email address to be validated.
        :type email: str
        :return: Returns True if the email is valid, False otherwise.
        :rtype: bool
        """
        email_regex = '^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z]{2,}$'
        return bool(re.match(email_regex, email))
      
    # ... Similar comments for other methods ...

GPT Response Overview

  1. In the examples above, we used the standards set by TypeDoc and Sphinx to add descriptions and type information to our methods.

  2. TypeDoc uses JSDoc-style comments, while Sphinx uses reStructuredText syntax. Both allow you to document your code in a structured, comprehensive, and readable way.

Benefits and Conclusion

Documentation provides several benefits. It improves code readability, eases maintenance, allows other developers to understand and use your code effectively, and even helps future-you remember what past-you did.

Tools like TypeDoc and Sphinx make this process standard, simple, and structured. Effective documentation is as essential as writing clean, efficient code.

Whether you're working in TypeScript or Python, TypeDoc and Sphinx can provide a streamlined way to create comprehensive documentation that benefits you and your team.

Was This Helpful?

If you found this blog post helpful, feel free to check out our other blog posts on using AI in software development at the Logobean Blog!

Blog CTA

Get Started For Free. No Signup Required.

1. Get started

Add your business name to instantly generate an endless selection of logos and brands.

Icon AI business name & slogan generator
Icon Select a business or general logo theme
Icon Select a logo name layout (for 2+ word names)
Icon Generate unlimited logos in seconds
Icon No sign up required
Start Logobean Logo Maker
Logobean logo maker get started
Logobean logo maker select styles live preview favorite

2. Select styles, live preview and favorite your logos

Select your logo styles to refine the generated logos, click any logo to view it in the live previews & logo style guide and favorite the logos that you love.

Icon Select styles to refine your generated logos
Icon Filter logo layouts, icons, colors, fonts & more
Icon Revolutionary & interactive logo previews
Icon Live & interactive logo style guide
Icon Save logos that you love to your favorites
Start Logobean Logo Maker

3. Edit and perfect your logo

Edit any logo to perfection using our intuitive logo and rich text editors.

Icon Intuitive logo editors for every logo layout
Icon Rich text editors for your name and slogan
Icon Icon, color and font selectors
Icon Smart icon coloring
Icon Live preview your logo whilst editing
Start Logobean Logo Maker
Logobean logo maker edit logo editor
Logobean logo maker select styles live preview favorite

4. Download your logo files & more

Once you've found the perfect logo, download and use your logo package instantly!

Icon High quality PNG & SVG logo files
Icon 100+ on-brand designs
Icon Ready-to-upload social media profile & cover images
Icon Brand color palette
Icon Manage your logos, brand and downloads on-going
Start Logobean Logo Maker

Ready to get started?