Coding with ChatGPT: A Two-Week Review of Daily Programming Tasks
As a software developer, I’m always looking for tools and technologies that can make my coding more efficient and productive. When I first came across ChatGPT, I was immediately captivated by its potential application in the realm of software development. Excited to explore its capabilities, I embarked on a two-week experiment, testing ChatGPT with my daily programming tasks.
As I went, I documented my experience. In this article, I’ll walk you there my discoveries and revelations that unfolded during these weeks of coding with ChatGPT. First, we’ll dive deep into the various functions and capabilities I used, such as code analysis and suggestions, code refactoring, debugging assistance, documentation generation, and code reviewing. There, I’ll showcase real-life code examples from my TypeScript, GraphQL, NestJS, and MongoDB projects. Next, I touch on 4 key takeaways on how it improved my coding experience. Lastly, I’ll finish up with some lessons I learned along the way.
Join me as I share firsthand my coding experience with ChatGPT.
Table Of Contents
- My two-week experiment with ChatGPT: Work & Project Context
- Five Ways to Use ChatGPT in the Development Process
- My Experience Coding with ChatGPT: 4 Key Benefits
- ChatGPT Code Analysis Reflection
- Lessons Learned While Using ChatGPT to Code
- My Advice for Developers Using ChatGPT
- Final Thoughts: Is ChatGPT a Good AI Tool for Writing Code?
My two-week experiment with ChatGPT: Work & Project Context
Integrating ChatGPT in my development tasks with TypeScript and RESTful APIs
As a software developer, I primarily work with TypeScript using frameworks, such as Nest.js to build scalable and maintainable applications. During this experiment, I focused on projects involving RESTful APIs, authentication, and database integration and actively incorporated ChatGPT into various coding tasks by leveraging its capabilities to streamline my workflow. Below is an overview of the specific tasks I performed using ChatGPT.
Setting the Stage: Project Overview and the Technologies Involved
To accurately gauge how useful ChatGPT is to me while I code, it’s important to understand my work context. I code for a web application that uses a tech stack combination of TypeScript, GraphQL, NestJS, and MongoDB. The application provides seamless data management for users and focuses on scalability and performance.
My role on the project involves developing backend services, designing and implementing GraphQL APIs, and optimizing database interactions. My goal with using ChatGPT as a coding tool is to enhance the quality of my code, improve my productivity, and ultimately deliver a more robust and efficient application.
My goal with using ChatGPT as a coding tool is to enhance the quality of my code, improve my productivity, and ultimately deliver a more robust and efficient application.
Let’s jump into some specific examples and insights from my real-world project and start looking at how I integrated ChatGPT into my development process and improved the quality of work I delivered.
Five Ways to Use ChatGPT in the Development Process
1. Writing new code with ChatGPT
When developing a new API endpoint using Nest.js, I asked ChatGPT to generate the boilerplate code for request validation and error handling. For example, I asked ChatGPT to provide the code for validating a user registration request. It quickly generated the necessary validation schema and error-handling logic using Nest.js decorators, which I then promptly pasted into my code base.
1import { IsString, IsEmail, Length } from 'class-validator';23export class UserRegistrationDto {4 @IsString()5 @IsEmail()6 email: string;78 @IsString()9 @Length(8, 20)10 password: string;11}
2. Debugging existing code
While working on an authentication module, I encountered an issue with token validation. I consulted with ChatGPT by sharing relevant code snippets and explaining the problem. It analyzed the code and pointed out an incorrect configuration setting that caused the token verification to fail. Here’s an example of the problematic code:
1// Incorrect code2const decodedToken = jwt.verify(token, process.env.JWT_SECRET);3
After ChatGPT flagged my error, I realized I had forgotten to specify the algorithm for token verification:
1// Corrected code2const decodedToken = jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] });3After finding my error in my code, I decided to try another test. I asked ChatGPT to help with a common debugging scenario involving a GraphQL mutation:4@Mutation(returns => User)5async createUser(@Args('input') input: CreateUserInput): Promise<User> {6 const newUser = new User(input);7 await newUser.save();89 return newUser;10}11
ChatGPT suggested that I ensure that the input object passed to the mutation is not null or undefined before creating the user:
1@Mutation(returns => User)2async createUser(@Args('input') input: CreateUserInput): Promise<User> {3 if (!input) {4 throw new BadRequestException('Invalid input');5 }67 const newUser = new User(input);8 await newUser.save();910 return newUser;11}12
ChatGPT proved to be a helpful companion in the debugging process, assisting in identifying and resolving issues.
3. Refactoring code for better performance
As the application grew, I wanted to optimize certain parts of the codebase. ChatGPT assisted me in this task by identifying areas for improvement. For instance, when working with database queries, I asked ChatGPT for guidance on optimizing a slow-performing query. It recommended using indexing and provided an example of an improved query:
1// Original slow query2const users = await this.userService.getUsersByRole('admin');34// Optimized query5const users = await this.userService.getAdminUsers();6
The optimized query improved the query performance by directly fetching users with the ‘admin’ role using the getAdminUsers method. This approach avoided unnecessary processing and reduced the number of database operations, resulting in faster response times and better overall performance. As a result, the application can efficiently handle user-related tasks, providing a smoother user experience, even as the user database grows.
After significantly enhancing the query performance, I wanted to perform another test refactoring code using a NestJS GraphQL resolver. Below is my code:
1@Resolver(of => User)2export class UserResolver {3 constructor(private userService: UserService) {}4 @Query(returns => User)5 async getUser(id: string): Promise<User> {6 const user = await this.userService.findById(id);7 if (!user) {8 throw new NotFoundException(`User with id ${id} not found`);9 }1011 return user;12 }13}14
ChatGPT’s suggested using NestJS built-in exception handling, instead of manually throwing exceptions. Below is the code it offered me:
1@Resolver(of => User)2export class UserResolver {3 constructor(private userService: UserService) {}45 @Query(returns => User)6 async getUser(@Args('id') id: string): Promise<User> {7 return this.userService.findByIdOrFail(id);8 }9}10
ChatGPT’s assistance in code refactoring was highly valuable. It provided recommendations to enhance code structure, readability, and performance.
4. Writing documentation
Documentation is crucial for collaborative development, so I got ChatGPT to generate initial documentation for the API endpoints. It swiftly generated a skeleton with essential details, such as the route (POST /users/register), a brief description of the endpoint, and the expected request payload structure. Also, it included information about the response format, outlining the returned user details.
It’s always important to go over what ChatGPT gives you, so I reviewed the generated documentation and added further details specific to my project, such as the expected format of the UserRegistrationDto and the specific UserDto structure for the registered user.
1/**2 * @route POST /users/register3 * @description Register a new user4 * @body {UserRegistrationDto} userRegistrationDto - The user registration details5 * @returns {UserDto} - The registered user details6 */7
It sped up the documentation process so much that I got it to generate documentation for a GraphQL resolver:
1/**2 * Retrieves a user by their ID.3 * @param {string} id - The ID of the user.4 * @returns {Promise<User>} - The retrieved user.5 */6@Query(returns => User)7async getUser(@Args('id') id: string): Promise<User> {8 return this.userService.getUserById(id);9}10
The generated documentation clearly explained each API endpoint, making it easier for other developers to understand and utilize my project’s GraphQL API. Leveraging the AI-powered capabilities of ChatGPT allowed me to streamline the documentation process and focus on fine-tuning the content to match the project’s requirements. Such a time-saver!
5. Reviewing existing code
I got ChatGPT to review existing code from both other developers and myself.
First, I used ChatGPT to review the Nest.js code submissions of other developers with whom I collaborate. It helped me identify potential code smells, provided suggestions for better code organization, and pointed out places where dependency injection could be optimized. For example, ChatGPT highlighted a class that could be converted into a Nest.js service to improve code modularity:
1// Original class2export class UserRepository {3 // ...4}56// Suggested Nest.js service7@Injectable()8export class UserService {9 constructor(private readonly userRepository: UserRepository) {}10 // ...11}12
The code modularity introduced by converting the original class into a Nest.js service, as suggested by ChatGPT, improves the app I’m working on in several ways. First and foremost, it enhances code organization and maintainability. By creating a separate UserService with its specific responsibilities, the codebase becomes more structured and easier to manage. This ensures that user-related functionalities are isolated and contained within the UserService, making it simpler to locate and update relevant code.
Second, I got ChatGPT to assist me in reviewing a NestJS service and enhancing the quality of the code:
1@Injectable()2export class ProductService {3 constructor(private productRepository: ProductRepository) {}45 async getProduct(id: string): Promise<Product> {6 return this.productRepository.findOne(id);7 }8}9
ChatGPT suggested that I add an error handling to handle cases where the product with the specified ID is not found:
1@Injectable()2export class ProductService {3 constructor(private productRepository: ProductRepository) {}45 async getProduct(id: string): Promise<Product> {6 const product = await this.productRepository.findOne(id);78 if (!product) {9 throw new NotFoundException(`Product with ID ${id} not found`);10 }1112 return product;13 }14}15
By incorporating ChatGPT’s suggestions, I improved the resilience and reliability of my service code.
My Experience Coding with ChatGPT: 4 Key Benefits
During my two-week experiment with ChatGPT, I had the opportunity to explore its capabilities and evaluate its performance in various aspects of software development. Here, I will delve deeper into my experience and provide detailed insights into the following areas:
- Ease of Use
- Learning Curve
- Performance and Speed
- Accuracy and Relevance of Suggestions
1. Ease of Use
One of the best features of ChatGPT is it’s easy! The setup process is straightforward and the user interface is intuitive, making it easy to interact with the AI model. Whether I needed help with code analysis, refactoring suggestions, or debugging help, ChatGPT provided quick and easy guidance.
For instance, when I got ChatGPT to simplify the process of defining GraphQL types in a NestJS application, I could easily describe the desired GraphQL type and receive accurate suggestions for generating the necessary decorators and fields. This not only saved me time but reduced the likelihood of introducing errors during the type definition process.
2. Easy Learning Curve
While it does take some time to learn how to use ChatGPT efficiently, I quickly became familiar with it and integrated it smoothly into my existing workflow. Having prior knowledge of TypeScript, GraphQL, NestJS, and MongoDB is invaluable in leveraging ChatGPT’s capabilities to its fullest extent.
Initially, I found it helpful to experiment with simpler tasks, such as generating basic code snippets or obtaining suggestions for minor refactorings. As I became more comfortable, I gradually increased the complexity of the tasks I entrusted to ChatGPT, such as debugging intricate code segments or optimizing performance-critical sections.
3. Quick Performance
ChatGPT provided near-instantaneous suggestions and insights throughout my experiment– allowing me to maintain a smooth development pace.
For instance, when debugging an API endpoint in a NestJS controller that involved data retrieval from a MongoDB collection, I encountered a performance bottleneck. By describing the issue to ChatGPT and providing relevant code snippets, it quickly analyzed the code and proposed a modification to the query structure. This suggestion improved the efficiency of the query and resolved the performance bottleneck, leading to significant gains in response time.
4. Accurate and Relevant Improvements & Suggestions
The accuracy and relevance of ChatGPT’s suggestions impressed me. It demonstrated a solid understanding of TypeScript, GraphQL, NestJS, and MongoDB, enabling it to provide valuable insights and recommendations tailored to the specific context of the codebase.
When it came to coding refactoring, ChatGPT’s suggestions were on point. For example, while optimizing the performance of a complex query, ChatGPT recommended the use of MongoDB indexes. By incorporating its recommendations, I was able to improve the response time of database queries significantly.
ChatGPT Code Analysis Reflection
ChatGPT proved to be a valuable tool for code analysis by providing insightful suggestions to improve code quality. Working with my AI-generated assistant, I felt like I had a knowledgeable coding partner by my side giving me valuable insights and guiding me towards cleaner and more optimized code. The suggestions went beyond simple syntax checks, delving into best practices and performance enhancements.
When I used the recommendations, I saw a significant improvement in the overall quality of my codebase. This experience showed me the transformative potential of AI-powered tools in software development, empowering us to write better code, enhance efficiency, and become better developers.
Lessons Learned While Using ChatGPT to Code
Be Mindful of Potential Ethical and Legal Issues
Using ChatGPT or any AI-powered tool in software development raises ethical and legal considerations. Be aware of any intellectual property rights, data privacy, and accountability issues that may arise like using ChatGPT to generate code snippets or assist in refactoring. Ensure that you have the necessary permissions or licenses for any third-party libraries or code that may be included. Lastly, be mindful of any potential privacy concerns when sharing code or data with the tool.
Leverage AI-Assisted Development for Routine Tasks
AI-assisted development tools like ChatGPT can significantly enhance software development, save time, and reduce the cognitive load of routine tasks like generating boilerplate code.
Learn when to use human knowledge over AI-generated responses
While AI-assisted development tools can be highly beneficial, it’s essential to strike the right balance between utilizing these tools and retaining the developer’s expertise. It’s crucial to understand the suggestions provided by ChatGPT, evaluate their correctness, and make informed decisions.
Remember, AI-generated code should always be reviewed and validated before being integrated into the project. Relying solely on AI-generated code without proper evaluation can lead to potential issues and hinder the quality of the software.
Consider Other AI-generated coding assistants
While ChatGPT is a powerful tool, it’s worth considering alternative AI coding assistants in the market. Each tool has its own strengths, weaknesses, and unique features. Some popular alternatives to explore include:
- Github Copilot: An AI coding assistant developed by GitHub, powered by OpenAI’s Codex. A full-stack developer reviewed this AI pair programming tool.
- CopilotX: An enhanced version of Copilot with additional features and improvements.
- AWS Code Whisperer: Amazon Web Services’ AI-powered coding assistant for various programming languages.
- Codex: OpenAI’s language model is designed specifically for code generation and completion.
- Kite: An AI-powered coding assistant that integrates with various IDEs and offers code suggestions.
- Deep TabNine: A code completion tool that uses machine learning to provide accurate code suggestions.
By exploring these alternatives, you can assess their suitability for your specific project requirements and find the tool that aligns best with your needs.
My Advice for Developers Using ChatGPT
Using ChatGPT as a day-to-day tool in software development requires a thoughtful approach. Here are some practical tips and recommendations for developers who want to incorporate ChatGPT into their workflow effectively:
- Start with simple tasks and gradually increase the complexity
- Learn to trust the tool but use common sense and critical thinking
- Use ChatGPT as a complementary tool, not a replacement for human expertise
- Time management to avoid over-reliance on AI-generated code
- Stay up-to-date on knowledge of AI and new features
Final Thoughts: Is ChatGPT a Good AI Tool for Writing Code?
After two weeks of testing ChatGPT in my projects that used a technology stack of TypeScript, GraphQL, NestJS, and MongoDB project, I learned how valuable of an assistant it is for software development. It helped me analyze code, provided useful suggestions, and made refactoring and debugging much easier.
When writing new code, ChatGPT offered relevant code snippets and improved my coding speed and accuracy. Its suggestions for refactoring also helped optimize the performance and readability of the code. Moreover, it generated documentation by extracting information from code comments, keeping my project’s documentation up-to-date.
I’m impressed by ChatGPT’s performance and will recommend it to developers interested in enhancing their software development process.