Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon

Simplifying Code Review using Google Bard

Save for later
  • 7 min read
  • 11 Jun 2023

article-image

Code reviews are an essential part of the software development process. They help improve the quality of code by identifying potential bugs and suggesting improvements. They ensure that the code is readable and maintainable. However, conducting code reviews takes time out of an engineer's busy schedule. There is also the potential that latent issues in the code may be overlooked. Humans do make mistakes after all. This is where Google Bard comes into play.

Bard is a tireless and efficient code reviewer that you can put to work anytime. It is a Large Language Model (LLM) that was trained on a massive dataset of text and code. White Bard is still listed as experimental, it has learned how to review and explain code written in many different programming languages.

How can Google Bard be used for code reviews?

Code reviews typically involve three basic steps: 

  1. Understand: The reviewer first reads the code and comprehends its purpose and structure.
  2. Identify: Potential bugs or issues are noted. Gaps in functionality may be called out. Error handling is reviewed, including edge cases that may not be handled properly.
  3. Optimize: Areas of improvement are noted, and refactoring suggestions are made. These suggestions may be in terms of maintainability, performance, or other area 

Fortunately, Bard can help in all three code review phases.

Ask Bard for an explanation of the code

Bard can generate a summary description that explains the purpose of the code along with an explanation of how it works. Simply ask Bard to explain what the code does. Code can be directly included in the prompt, or you can reference a GitHub project or URL. Keep in mind, however, that you will get more detailed explanations when asking about smaller amounts of code. Likewise, if you use the following prompt asking about the BabyAGI repo, you will get a summary description.

simplifying-code-review-using-google-bard-img-0

Image 1: Google Bard’s explanation on Baby AGI

 The interesting thing about Bard’s explanation is that not only did it explain the code in human terms, but it also provided a pseudo-code snippet to make it easy to comprehend. This is impressive and extremely useful as a code reviewer. You have a roadmap to guide you through the rest of the review. Developers who are unfamiliar with the code or who need to understand it better can leverage this Bard capability.

Given that LLMs are very good at text summarization, it is not surprising that they can do the same for code. This gives you a foundation for understanding the AGI concept and how BabyAGI implements it. Here is a highlight of the overview code Bard provided:

def create_plan(text):
    """Creates a plan that can be executed by the agent."""

    # Split the text into a list of sentences.
    sentences = text.split(".")

    # Create a list of actions.
    actions = []
    for sentence in sentences:
        action = sentence.strip()
        actions.append(action)

    return actions

def main():
    """The main function."""

    # Get the task from the user.
    task = input("What task would you like to complete? ")

    # Generate the text that describes how to complete the task.
    text = get_text(task)

    # Create the plan.
    plan = create_plan(text)

    # Print the plan.
    print(plan)

if __name__ == "__main__":
    main()

BabyAGI uses a loop to continue iterating on nested tasks until it reaches its goal or is stopped by the user. Given a basic understanding of the code, reviews become much more effective and efficient.

Identifying bugs using Bard

You can also ask Bard to identify potential bugs and errors. Bard will analyze the code and look for patterns associated with bugs. It will point out edge cases or validations that may be missing. It also looks for code that is poorly formatted, has unused variables, or contains complex logic.

 Let’s have Bard review its own summary code shown above. The get_text function has been modified to use the Bard API. Our review prompt is as follows. It includes the code to review inline.

 Review the following Python code for potential bugs or errors:

 

import requests
import json
 
def get_text(task):
    """Generates text that describes how to complete a given task."""
     bard = Bard() 
     answer = bard.get_answer(task) 
     return answer['content']
 
def create_plan(text):
    """Creates a plan that can be executed by the agent."""
    # ... remainder of code omitted here for brevity ...
simplifying-code-review-using-google-bard-img-1

Image 2: Google Bard’s explanation of reviewed code

Unlock access to the largest independent learning library in Tech for FREE!
Get unlimited access to 7500+ expert-authored eBooks and video courses covering every tech area you can think of.
Renews at €18.99/month. Cancel anytime

 Bard pointed out a number of potential issues. It noted that error handling is missing around the Bard API call. It commented that input validations should be added, as well as default values that could make the code more user-friendly.

Optimizations using Google Bard

Bard already provided some suggested improvements during its review. You can also ask Bard specifically to suggest optimizations to your code. Bard does this by analyzing the code and looking for opportunities to improve its efficiency, reliability, or security. For example, Bard can suggest ways to simplify code, improve performance, or make it more secure.

 Let’s do this for the main BabyAGI Python script. Instead of referencing the GitHub repository as we did in the explanation phase, we provide the main loop code inline so that Bard can provide more detailed feedback. The structure of the prompt is similar to the prior phase.

 Review the following Python code for potential optimizations:

def main():
    loop = True
    while loop:
        # As long as there are tasks in the storage…
        # ... remainder of function omitted here for brevity ...

 

simplifying-code-review-using-google-bard-img-2

Image 3: Google Bard’s explanation of reviewed code 

While the print suggestion is not particularly helpful, Bard does make an interesting suggestion regarding the sleep function. Beyond pointing out that it may become a bottleneck, it highlights that the sleep function used is not threadsafe. While time.sleep is blocking, the use of asyncio.sleep is non-blocking. Using the asyncio the method asks the event loop to run something else while the await statement finishes its execution. If we were to incorporate this script into a more robust web application, this would be an important optimization to make.

General tips for using Bard during code reviews.

Here are some tips for using Bard for code reviews:

  •  Be specific where possible. For example, you can ask for specific types of improvements and optimizations during your code review. The more specific the request, the better Bard will be able to respond to it.
  • Provide detailed context where needed. The more information Bard has, the more effective the review feedback will be.
  • Be open to feedback and suggestions from Bard, even if they differ from your own opinions. Consider and evaluate the proposed changes before implementing them.

Conclusion

Google Bard is a powerful tool that can be used to improve the quality of code. Bard can help to identify potential bugs and errors, suggest improvements, and provide documentation and explanations. This can help to improve the efficiency, quality, and security of code.

If you are interested in using Google Bard for code reviews, you can sign up for the early access program. To learn more, visit the Google Bard website.

Author Bio

Darren Broemmer is an author and software engineer with extensive experience in Big Tech and Fortune 500. He writes on topics at the intersection of technology, science, and innovation.

 LinkedIn