[

🎉

G2 Spring 2024 Report] Hatica does it again! Wins Momentum Leader, Best Est. ROI and Users Love Us badge among many!Read More ->

AI2023-10-16

9 Ways Amazon CodeWhisperer Can Boost Your Productivity

Discover the 10 powerful methods to enhance your productivity with Amazon CodeWhisperer. Streamline your development, and save time. Explore now!
10 Ways Amazon CodeWhisperer Can Boost Your Productivity

Amazon CodeWhisperer, a generative AI tool developed by Amazon is your go-to coding companion that integrates with your code editor. It boasts support for multiple programming languages, from Python to JavaScript and Java etc. 

Designed to offer a seamless and efficient coding experience, it comes packed with features like syntax highlighting, code completion, and code refactoring. The best part? Its user-friendly and customizable interface allows you to mold your workspace to suit your unique needs.

In this article, we'll explore 10 ways you can leverage Amazon CodeWhisperer to optimize your workflow, using a simple Python project as our focus.

What Is Amazon CodeWhisperer?

As developers, we are perpetually on the lookout for tools that can amplify productivity and streamline our workflows. Amazon CodeWhisperer emerges as a potent solution to expedite the development process while enhancing code quality and security.
Amazon’s Code Whisperer is designed to empower developers by providing real-time code suggestions, aiding in code comprehension, enhancing security scans, and seamlessly integrating with popular programming languages and IDEs. 

One of the standout features of Amazon CodeWhisperer is its ability to generate code suggestions in real-time. Drawing from an extensive database of billions of lines of code, CodeWhisperer can suggest anything from code snippets to complete functions, all based on your comments and existing code. 

This feature is particularly valuable for reducing the time spent on writing boilerplate code and navigating unfamiliar APIs.

CodeWhisperer anticipates your coding needs with real-time suggestions while you type. And if inspiration doesn't strike immediately, you can invoke suggestions manually by simply hitting the Option + C (Mac) or Alt + C (Windows) keyboard keys. 

It generates an array of choices for you to choose from. Seamlessly cycle through these generated options to tailor your code to perfection. CodeWhisperer isn't just about speeding up development. It's also focused on elevating the quality and security of your codebase. The tool offers built-in security scans that can detect hard-to-find vulnerabilities. These scans align with industry best practices, such as those outlined by the Open Web Application Security Project (OWASP). Moreover, CodeWhisperer provides actionable suggestions for remediating these vulnerabilities, enabling developers to create more secure code.

Leveraging Amazon CodeWhisperer To Boost Developer Productivity 

Would you believe it if we told you CodeWhisperer helped developers to improve their productivity by 27%, and improved their workflow speed by a whooping 57%. 

Amazing, isn’t it?

Know how you can harness the full potential of Amazon CodeWhisperer to boost your productivity, and build efficient workflows: 

AI-Generated Code Suggestions

Embrace the AI-generated code suggestions to accelerate development and reduce manual coding effort.

For instance, let's create a function to add a new task.

def add_task(tasks, new_task):
    tasks.append(new_task)

When creating functions in our Python task manager, CodeWhisperer can provide instant code suggestions. With each keystroke, CodeWhisperer offers suggestions that align with the context, saving time and reducing potential errors.

Refactoring is made easy with CodeWhisperer. If we decide to rename our add_task function to create_task, CodeWhisperer helps us propagate the change throughout the codebase.

def create_task(tasks, new_task):
    tasks.append(new_task)

Let’s say you're in the process of writing a function to calculate the factorial of a number. Let's see how CodeWhisperer can enhance this process. Suppose you start writing the following code:

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)

As you type the code, CodeWhisperer's AI engine actively analyzes your context and coding style. 

When you reach the point where you're multiplying n with the recursive call to factorial(n - 1), CodeWhisperer recognizes the pattern and offers a tailored code suggestion that aligns with your coding preferences. 

It anticipates your intention and suggests a more concise way to write the recursive call.

def factorial(n):
    if n == 0:
        return 1
    else:
        return n * factorial(n - 1)  # suggested line

2. Security Prioritized 

Leverage the built-in security scans to detect vulnerabilities and follow the provided suggestions to enhance code security. Consider this example where CodeWhisperer detects a potential vulnerability related to user input.

def create_task(tasks, new_task):
    if '<script>' in new_task:
        raise ValueError("Potential XSS vulnerability detected.")
    tasks.append(new_task)

3. Freedom To Choose Your Stack 

Take advantage of CodeWhisperer's compatibility with a range of programming languages and IDEs. CodeWhisperer stands as a versatile companion, adapting seamlessly to a wide spectrum of programming languages. 

Programming languages like Java, Python, JavaScript, and TypeScript find their unique place within CodeWhisperer's capabilities, offering tailored assistance for your coding endeavors. And extends further to languages like Ruby, Go, PHP, C++, etc. 

It also integrates harmoniously with renowned platforms such as AWS SageMaker Studio, JupyterLab, Visual Studio Code, and JetBrains IDEs. This integration fosters an environment where your chosen stack aligns seamlessly with your coding preferences. 

Whether your focus is on machine learning, dynamic scripting, or comprehensive code editing, CodeWhisperer enables you to work within a familiar and productive setting.

4. Thoughtful, and Responsible Coding 

CodeWhisperer empowers you to seamlessly incorporate established algorithms. By indicating the specific algorithm you intend to use for a given coding challenge, CodeWhisperer readily assists in its implementation.

actors = [
    {"name": "Tom", "age": 35},
    {"name": "Emma", "age": 28},
    {"name": "John", "age": 42},
    # Add more actors here...
]

def merge_sort(arr):
    if len(arr) <= 1:
        return arr

    middle = len(arr) // 2
    left = arr[:middle]
    right = arr[middle:]

    return merge(merge_sort(left), merge_sort(right))

def merge(left, right):
    result = []
    left_index = 0
    right_index = 0

    while left_index < len(left) and right_index < len(right):
        if left[left_index]["age"] < right[right_index]["age"]:
            result.append(left[left_index])
            left_index += 1
        else:
            result.append(right[right_index])
            right_index += 1

    result.extend(left[left_index:])
    result.extend(right[right_index:])
    return result

sorted_actors = merge_sort(actors)
print(sorted_actors)

5. Easily Create Sample Data

Generating sample data is often a mundane task. CodeWhisperer transforms this task into an art form. By creating patterns and dummy data, CodeWhisperer saves you time and adds creativity to your projects. You never have to worry about the mundane task of data generation the same way again.

import random

user_names = ["Alice", "Bob", "Charlie", "David", "Emma", "Frank", "Grace", "Henry"]

fake_users = [
    {"name": user_names[0], "id": f"user{random.randint(1, 100)}", "target": random.choice([True, False])},
    {"name": user_names[1], "id": f"user{random.randint(1, 100)}", "target": random.choice([True, False])},
    {"name": user_names[2], "id": f"user{random.randint(1, 100)}", "target": random.choice([True, False])},
    {"name": user_names[3], "id": f"user{random.randint(1, 100)}", "target": random.choice([True, False])},
    {"name": user_names[4], "id": f"user{random.randint(1, 100)}", "target": random.choice([True, False])},
    {"name": user_names[5], "id": f"user{random.randint(1, 100)}", "target": random.choice([True, False])},
    {"name": user_names[6], "id": f"user{random.randint(1, 100)}", "target": random.choice([True, False])},
    {"name": user_names[7], "id": f"user{random.randint(1, 100)}", "target": random.choice([True, False])},
]

print(fake_users)

6. Simplifying the Complex, Regular Expressions

Regular expressions can be cryptic, but CodeWhisperer is here to simplify them. While it can't decode natural language into custom regex (yet), it masters common patterns. This feature eases complex string manipulations, ensuring your code remains clear and concise.

import re

def validate_email(email):
pattern = r'^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$'
return re.match(pattern, email.lower()) is not None

7. Speak Fluent API

When APIs are cryptic, CodeWhisperer becomes our interpreter. Adding timestamps to our tasks? Watch as it interprets our intention:

from datetime import datetime

def add_task_with_timestamp(tasks, new_task):
    timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    tasks.append(f"{timestamp} - {new_task}")

8. Precision Through Unit Tests

Unit testing is your safety net in coding. CodeWhisperer takes this a step further by suggesting explicit and edge-case unit tests. As your coding ally, it propels you towards comprehensive testing, ensuring your code is robust and reliable.

import unittest

class Folder:
    def __init__(self, name, parent=None):
        self.name = name
        self.children = []
        self.parent = parent

    def add_child(self, child):
        if child not in self.children:
            self.children.append(child)
            child.parent = self

    def remove_child(self, child):
        if child in self.children:
            self.children.remove(child)
            child.parent = None

class TestFolderMethods(unittest.TestCase):
    def test_add_existing_folder(self):
        root = Folder("root")
        child = Folder("child")
        root.add_child(child)
        root.add_child(child)
        self.assertEqual(len(root.children), 1)

if __name__ == '__main__':
    unittest.main()

9. Code Documentation Made Easy, and Effortless

CodeWhisperer not only generates code but also helps document it. By leveraging code comment prompts, I've effortlessly produced informative docstrings and comments that enhance code readability and collaboration. In this case, let’s ask CodeWhisperer to document our previous unit test.

import unittest

# Define the Folder class to represent a folder structure
class Folder:
    def __init__(self, name, parent=None):
        # Initialize folder attributes
        self.name = name
        self.children = []  # Initialize an empty list to store child folders
        self.parent = parent  # Set the parent folder (if any)

    # Method to add a child folder
    def add_child(self, child):
        # Check if the child is not already in the list
        if child not in self.children:
            self.children.append(child)  # Add the child to the list
            child.parent = self  # Set the parent of the child

    # Method to remove a child folder
    def remove_child(self, child):
        # Check if the child is in the list
        if child in self.children:
            self.children.remove(child)  # Remove the child from the list
            child.parent = None  # Clear the parent of the child

# Define a test class for Folder methods
class TestFolderMethods(unittest.TestCase):
    # Test case: Adding an existing folder should not add duplicate
    def test_add_existing_folder(self):
        # Arrange: Create a root folder and a child folder
        root = Folder("root")
        child = Folder("child")

        # Act: Add the child folder twice to the root folder
        root.add_child(child)
        root.add_child(child)

        # Assert: Check that only one child was added
        self.assertEqual(len(root.children), 1)

# Run the unit tests if the script is executed directly
if __name__ == '__main__':
    unittest.main()

Bottom Line: Accelerate Your Workflow With CodeWhisperer

Amazon CodeWhisperer has redefined how I approach coding. It's not just a tool; it's an ally that enhances my coding abilities. By employing these techniques, I've unlocked a realm of possibilities that accelerate my coding journey, refine my code quality, and amplify my overall productivity.

Install CodeWhisperer, embrace its capabilities, and embark on a journey where your coding superpowers reach new heights. As we, the CodeWhisperer community, continue to innovate, the boundaries of what's possible will expand even further. Join the symphony of superpowers and redefine how you code. 

The techniques highlighted here are your key to unlocking this power. As you traverse the realm of typing less, generating elegant functions, crafting classes, conquering algorithms, writing impeccable tests, and more, remember that CodeWhisperer is your steadfast companion, enhancing every facet of your coding voyage. 

Subscribe to the Hatica blog to read more about developer productivity, engineering success, and AI-led code development.

Subscribe to Hatica's blog

Get bi-weekly insights straight to your inbox

Share this article:
Table of Contents
  • What Is Amazon CodeWhisperer?
  • Leveraging Amazon CodeWhisperer To Boost Developer Productivity 
  • AI-Generated Code Suggestions
  • 2. Security Prioritized 
  • 3. Freedom To Choose Your Stack 
  • 4. Thoughtful, and Responsible Coding 
  • 5. Easily Create Sample Data
  • 6. Simplifying the Complex, Regular Expressions
  • 7. Speak Fluent API
  • 8. Precision Through Unit Tests
  • 9. Code Documentation Made Easy, and Effortless
  • Bottom Line: Accelerate Your Workflow With CodeWhisperer

Ready to dive in? Start your free trial today

Overview dashboard from Hatica