Amazon Q Developer (AI for software development)

What does it do for you? To try it out... Web IDE CLI
Chat Chat
Learn new things, explain code, refactor code, generate new code snippets from scratch Type a question, or select your code and right click, then Amazon Q ➜ Explain
Explore Explore
Ask about your AWS resources, query and filter with natural language Chat in AWS console, type "list/show my S3 buckets"
Suggestions Suggestions
Smart suggestions pop up as you type, saving you time and effort Just start typing in IDE or CLI, press tab to accept
Agent Agent
Describe a larger feature or major refactor to implement across multiple files, get a code diff back Type /dev in chat, describe what you want to build
Code Scans Code Scans
Automatically detect potential problems or vulnerabilities, explain or automatically fix them Open IDE command palette, select "Amazon Q: Run Project Scan"
Transformation Transformation
Automatically refactor entire projects between major language versions Type /transform in chat
Create an AWS Builder ID to try Amazon Q Developer in your IDE, at no cost, no credit card required

Basic Chat (Best practices for prompting)

Goal Example Prompt Technique Example Output
Get a high level overview of a popular topic while avoiding biased content and marketing What are the pros and cons of using React? Speak plainly, be concise, and avoid buzzwords

Here are some key pros and cons of using React, explained plainly and concisely:

Pros:

  • Reusable components: Write code once, use it multiple times across your app.
  • Fast performance: Uses a virtual DOM for efficient updates.
  • Easy to learn basics: Simple core concepts make it accessible for beginners.
  • Large community: Lots of resources, libraries, and support available.
  • Flexible: Can be used with many other tools and libraries.
  • Mobile development: Skills transfer well to React Native for building mobile apps.

Cons:

  • Frequent updates: Keeping up with changes can be challenging.
  • JSX complexity: Mixing JavaScript and HTML can be confusing at first.
  • Lack of full framework features: Requires additional libraries for routing, state management, etc.
  • Steep learning curve for advanced concepts: While basics are easy, mastering React takes time.
  • Overkill for simple websites: Might be unnecessary for basic static pages.

Overall, React is powerful for building complex, interactive web applications, but it may be more than needed for simpler projects.

Challenge statements by asking for the reverse viewpoint After Q Developer responds to your previous ask, in the same chat try: Now explain the reverse viewpoint

Here's the reverse viewpoint on the pros and cons of using React:

Cons:

  • Reusable components: Extra effort required to make truly reusable components across a large codebase.
  • Fast performance: Virtual DOM can be overkill for simple apps, adding unnecessary complexity.
  • Easy to learn basics: Basics are easy, but mastering React takes significant time and effort.
  • Large community: Too many options and opinions can be overwhelming, especially for beginners.
  • Flexible: With flexibility comes the need to make more decisions and integrate multiple libraries.
  • Mobile development: Separate skills required for React Native, adding to the learning curve.

Pros:

  • Frequent updates: Keeps the library modern and addresses issues quickly.
  • JSX complexity: Allows clean separation of concerns between markup and logic.
  • Lack of full framework features: Allows you to choose the right tools for your specific needs.
  • Steep learning curve for advanced concepts: Encourages developers to deeply understand core concepts.
  • Overkill for simple websites: Robust enough to handle complex requirements if needed.

From this viewpoint, the perceived cons of React can actually be seen as pros in certain situations. The flexibility and lack of opinionated solutions allow for more customization. The learning curve ensures developers truly understand the library. And while the basics are easy, mastering React is seen as a worthwhile investment for building robust and scalable applications.

Always dig deeper to make sure you haven't missed something What else do I need to know?

Here are some additional important points to know about React:

  • Virtual DOM: React uses a virtual DOM to optimize rendering, which improves performance for complex applications.
  • One-way data flow: React follows a unidirectional data flow, which makes it easier to understand how data changes affect the application.
  • React Native: You can use React to build mobile apps with React Native, sharing much of the codebase between web and mobile versions.
  • State management: For larger applications, you might need additional libraries like Redux or MobX to manage application state effectively.
  • Server-side rendering: React supports server-side rendering, which can improve initial load times and SEO.
  • Hooks: Introduced in React 16.8, Hooks allow you to use state and other React features in functional components without writing classes.
  • Component lifecycle: Understanding how React components mount, update, and unmount is crucial for building efficient applications.
  • Testing: React's component-based architecture makes it relatively easy to test individual parts of your application.
  • Build tools: Most React projects use build tools like webpack or Create React App to bundle and optimize the application.
  • Ecosystem: React has a rich ecosystem of libraries and tools, but choosing the right ones for your project can be challenging.

Remember, while React is powerful and widely used, it's important to evaluate whether it's the right tool for your specific project needs.

Write justifications for a decision I want to build an API server using Node.js and need to explain to coworkers why this is a good idea

Building an API server using Node.js is a great choice for several reasons:

  • Performance : Node.js is designed to handle a large number of concurrent connections with minimal overhead, making it ideal for building scalable and high-performance APIs.
  • Non-blocking I/O : Node.js uses an event-driven, non-blocking I/O model, which allows it to handle multiple requests concurrently without creating additional threads or processes, resulting in better resource utilization and scalability.
  • JavaScript Everywhere : Since Node.js uses JavaScript, you can write both the server-side and client-side code in the same language, making it easier for developers to share code and switch between front-end and back-end development.
  • Ecosystem and Packages : Node.js has a vast ecosystem of open-source packages and libraries available through npm (Node Package Manager), which can help you quickly build and integrate various features into your API server.
  • Real-time Applications : Node.js is well-suited for building real-time applications, such as chat servers, live-updating dashboards, and collaborative tools, due to its event-driven nature and support for WebSockets.
  • Microservices Architecture : Node.js is lightweight and modular, making it a popular choice for building microservices architectures, where different components of an application can be developed and deployed independently.

While Node.js is an excellent choice for building APIs, it's important to note that it may not be the best fit for every use case, such as CPU-intensive tasks or applications that require long-running computations. In such cases, other technologies or programming languages might be more suitable.

Ensure that you didn't forget important details I want to make this code more performant. Ask me followup questions to answer more accurately.

I'd be happy to help you improve the performance of this code. To provide more accurate suggestions, I'll need some additional information. Here are a few follow-up questions:

  • Which specific function or part of the code are you most concerned about in terms of performance?
  • Have you identified any particular bottlenecks or slow operations in the current implementation?
  • What is the typical size of the data you're working with? For example, how many groceries are usually in a shopping list?
  • Are you experiencing any specific issues, such as timeouts or high latency?
  • Are there any particular performance goals you're trying to achieve? For example, reducing response time by a certain percentage or handling a specific number of requests per second?
  • Are you open to architectural changes, or do you prefer optimizations within the current structure?
  • Are there any constraints we need to consider, such as memory limitations or specific AWS service quotas?

Once you provide more details about these aspects, I'll be able to offer more targeted and effective suggestions for improving the performance of your code.

Challenge an existing assumption I want to build an API server using Rust. What might make me reconsider this choice?

While Rust is an excellent choice for building high-performance API servers, there are some factors you might want to consider before committing to it:

  • Learning curve: Rust has a steep learning curve, especially for developers coming from higher-level languages. Its unique concepts like ownership, borrowing, and lifetimes can be challenging to grasp initially.
  • Development speed: Due to Rust's strict compiler and safety checks, development might be slower compared to more dynamic languages like Python or JavaScript, especially during the initial stages of a project.
  • Ecosystem maturity: While Rust's ecosystem is growing rapidly, it may not be as mature as those of more established languages. You might find fewer libraries, frameworks, or tools for certain specialized tasks.
  • Team expertise: If your team is not familiar with Rust, there could be a significant ramp-up time and potential productivity loss during the learning phase.
  • Hiring challenges: Finding experienced Rust developers can be more difficult compared to developers proficient in more widely-used languages.
  • Compile times: Rust's compile times can be longer than those of other languages, which might impact development workflow and CI/CD pipelines.
  • Overkill for simple projects: If you're building a straightforward API that doesn't require high performance or low-level control, using Rust might be overengineering.
  • Interoperability: If you need to integrate with existing systems or libraries written in other languages, it might be more challenging with Rust compared to more widely-used languages.
  • Runtime performance vs. development speed trade-off: While Rust offers excellent runtime performance, the development process might be slower. For projects where rapid development is more critical than peak performance, other languages might be more suitable.
  • Community size: Although growing, the Rust community is smaller compared to more established languages, which might mean less community support and fewer resources.

That being said, Rust also offers significant advantages for API development, such as excellent performance, strong safety guarantees, and efficient memory usage. If these benefits align with your project requirements and you're willing to invest time in learning and using Rust, it can be an excellent choice for building robust and efficient API servers.

Learn about a particular code file What does Window.vue do?

The Window.vue file is a Vue.js component that provides a draggable and resizable window functionality. It allows you to create and manage windows within a Vue.js application. Here's a breakdown of what the component does:

  • Imports : It imports the necessary dependencies, including ref from Vue and the useWindowStore from a Pinia store called windows.
  • Props : It defines two props: id and parameters. The id prop is likely used to identify the window, while the parameters prop contains information about the window's position, size, and z-index.
  • Dragging : The component implements drag and drop functionality for the window. When the user starts dragging the window, the dragStart function is called, which saves the starting mouse cursor position. When the user stops dragging, the dragEnd function is called, which calculates the new position of the window based on the mouse movement and updates the window's position accordingly. It also ensures that the window stays within the viewport boundaries.
  • Window Surfacing : The windowClicked function is called when the user clicks on the window, and it calls the surfaceWindow action from the windowStore to bring the clicked window to the front.
  • Template : The template defines the structure of the window component. It includes a draggable div element that represents the window itself, with styles applied based on the parameters prop. The window has a header area with a close button and a content area where you can pass content using slots.
  • Styles : The component includes styles for the window, including the header area, content area, and the close button. It also includes styles for the dragging functionality, such as the hide-draggable class, which is used to temporarily hide the window during dragging.

Overall, the Window.vue component provides a reusable and customizable way to create draggable and resizable windows within a Vue.js application. It can be used in various scenarios where you need to display multiple windows or panels within the same application.

Learn more about Q Developer chat

@workspace (Automatically use one or more indexed files to answer questions)

Goal Example Prompt Technique Example Output
Learn an unfamiliar codebase What technologies are used in this @workspace?

Based on the code snippets provided, this project appears to use the following key technologies:

  • Vue.js: This is a progressive JavaScript framework for building user interfaces. The code uses Vue 3 features, as evidenced by the use of the Composition API (e.g., defineProps, defineEmits, ref, computed) and <script setup> syntax.
  • Pinia: This is the state management library being used, as seen in the imports like import { defineStore } from 'pinia' and import { storeToRefs } from 'pinia'.
  • WebSockets: The project seems to use WebSockets for real-time communication between the client and server, as indicated by the socket-related code in the socket.js store.
  • Component-based architecture: The project is structured using Vue components (e.g., DetailedItem.vue, MeWindow.vue, Window.vue).
  • CSS: For styling the components, as seen in the <style> sections of the Vue files.
  • JavaScript (ES6+): The project uses modern JavaScript features like arrow functions, template literals, and destructuring.
  • Single File Components (SFC): The .vue files combine template, script, and style in a single file, which is a Vue.js feature.
  • Reactive programming: The use of ref, computed, and Pinia stores indicates a reactive approach to managing and updating data.
  • Custom event handling: The code uses Vue's custom event system with $emit and defineEmits.
  • Drag and drop functionality: As seen in the DetailedItem.vue component with draggable attribute and drag event handlers.

This appears to be a client-side application, likely part of a larger system that includes a server-side component (given the WebSocket communication). The application seems to be related to managing items, skills, and character attributes, possibly for a game or inventory management system.

Double-check your overall code quality What improvements should I make to the code in this @workspace? Be concise

Based on the Vue component code provided, here are some concise suggestions for improvement:

  • Use destructuring to simplify props access: const { item } = props instead of const item = props.item.
  • Consider using v-bind shorthand (:) consistently for attribute binding.
  • Utilize computed properties for styleHelper instead of a method for better performance.
  • Use template literals for string interpolation in the template, e.g., `Weight: ${item.weight}`.
  • Consider using v-for to render item details, reducing repetitive template code.
  • Implement proper error handling in dragEnd function.
  • Use emits option to declare emitted events for better documentation.
  • Consider using CSS variables for repeated values like colors and border widths.
  • Use more specific selectors in CSS to avoid potential conflicts.
  • Add proper accessibility attributes for draggable elements.

These changes can make your code more efficient, maintainable, and aligned with Vue.js best practices.

Understand the flow of logic for a feature How does window surfacing work in this @workspace

Based on the code provided, window surfacing in this application is handled primarily through the useWindowStore and the Window.vue component. Let's break down how it works:

  • Z-Index Management: In the windows.js store file, there's a maxZIndex variable that keeps track of the highest z-index. This is used to ensure that the most recently interacted window appears on top.
  • Surfacing Function: The windowStore.surfaceWindow(props.id) function is called in two scenarios within the Window.vue component:
    • When dragging ends: function dragEnd(e) { windowStore.surfaceWindow(props.id); // ... other code }
    • When the window is clicked: function windowClicked() { windowStore.surfaceWindow(props.id); }
  • Z-Index Application: In the template of Window.vue, the z-index is applied dynamically: <div ... :style="{ ..., zIndex: props.parameters.zIndex }" ...>
  • Store Implementation: Although not fully visible in the provided code snippets, the surfaceWindow function in the useWindowStore likely updates the z-index of the specified window to be higher than all others, effectively bringing it to the front.
  • Reactive Updates: Since the store is using Vue's reactivity system (with ref and defineStore from Pinia), any changes to the window's z-index in the store will automatically update the component's rendering.

In summary, window surfacing works by:

  1. Detecting user interactions (clicks or drag ends) on a window.
  2. Calling the surfaceWindow function in the store with the window's ID.
  3. Updating the z-index of that window in the store to be higher than all others.
  4. Reactively applying the new z-index to the window's DOM element.

This system ensures that the most recently interacted window always appears on top of others, providing a natural and expected behavior for overlapping windows in the user interface.

Assume a custom persona, use it for accomplishing the task Create file .q/NODE_JS:
NODE_JS

Only when I explicitly ask for code, follow this guidance:

- Only provide Node.js JavaScript code, unless I explicitly ask for another language
- I always use AWS SDK v3
- Unless otherwise requested, only provide the piece of code without any further explanation and commentary
- I am an expert in Node.js and I did not need a walk through
            

Prompt:
@workspace NODE_JS How do I upload a local file to S3?

Here's a Node.js code snippet using AWS SDK v3 to upload a local file to S3:

import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
import { readFile } from "fs/promises";

const s3Client = new S3Client({ region: "us-west-2" });

async function uploadFileToS3(bucketName, key, filePath) {
  const fileContent = await readFile(filePath);
  
  const params = {
    Bucket: bucketName,
    Key: key,
    Body: fileContent,
  };
  
  try {
    const command = new PutObjectCommand(params);
    await s3Client.send(command);
    console.log(`File uploaded successfully to ${bucketName}/${key}`);
  } catch (error) {
    console.error("Error uploading file:", error);
  }
}

// Usage
uploadFileToS3("your-bucket-name", "path/to/object-key", "/path/to/local/file");
            

Read more
Learn more about @workspace

/dev (Generate larger code diffs for more complex tasks)

Goal Example Prompt Technique Example Result
Refactor an entire application /dev Transform this project using the 12 factor app approach and also generate a step-by-step instruction in a README.md file after refactoring is complete. Read more
Add observability to an application /dev Add support for OpenTelemetry. Create traces for each function in the microservice, as well as the nested functions invoked. Read more
Break up a monolith application, update infrastructure as code
/dev Refactor the backend logic to improve clarity and scalability:

- Split the logic into separate Lambdas, keeping the
code clean and well-documented.
- Share common functionality across Lambda functions
to avoid duplication.
- Keep permissions locked down.
- Update the Infrastructure as Code to support the
changes. 
Watch video
Improve the code documentation /dev Add JSDoc style comments to all functions in this project. Also add a README.md explaining the project structure and usage.
Find missing test cases, add unit tests /dev Explore this project and find functions that are missing important test cases. Add unit tests to cover any serious gaps.
Containerize an existing application /dev Add a Dockerfile and a script for building and running the application as a container
Bootstrap a brand new project with a given template
/dev Create a Node.js project for a basic hit counter application with the following structure:
.
├── iac/
│ ├── dynamodb-table.yml
│ └── fargate-service.yml
├── models/
│ └── counter.js
├── routes/
│ ├── healthcheck.js
│ └── increment-counter.js
├── tests/
│ ├── healthcheck.test.js
│ └── increment-counter.test.js
├── Dockerfile
├── build-and-deploy.sh
├── index.js
└── package.json
            
Watch Video
Guide a complex refactor Code:
/* TODO: Detect network failures and retry up to three times with exponential backoff */
function dispatch() {
  
}

/* TODO: Make sure we properly break large payloads into 1MB chunks */
function dispatchData() {
  
}

/* TODO: Ensure there is an 10MB upper limit on payload size */
function acceptInboundData() {
  
}
            

Prompt:
/dev Implement all TODO comments in this project
Learn more about /dev