Techniques and Technologies
How Coding Benefits from AI
If you’re a programmer or learning to program, generative artificial intelligence (also known as GenAI) can help you be more productive, make fewer mistakes, and learn new skills and languages faster, as you discover in this chapter. In the process, you work with some tools to get a taste of what’s available. All the topics in this chapter are described in detail in later chapters.
Although you might be able to use AI to generate working computer programs without knowing how to code, I strongly discourage you from doing this — especially if you plan to deploy anything you generate. Generative AI doesn’t know how to program. If you don’t know how to code either, there’s a good chance that code you create with AI will have serious security problems, functionality problems, or worse.
Banishing Boring Tasks
One of the most basic and useful things you can do with the current crop of generative AI models is to use them to generate the types of code programmers lovingly refer to as boilerplate code
The term boilerplate dates to the 19th century, when steel plates were used as tem plates for making steam boilers.
Boilerplate code is the stuff that’s the same or nearly the same in every file or every project. No one likes to write boilerplate code, but we have to do it because the code we want to write (the fun stuff) won’t work without the boilerplate
Spotting boring tasks
To identify tasks that can be automated with AI, think about the tasks that you do repeatedly in multiple projects. JavaScript developers might select an element in the browser window, such as a button, and attach to it an event listener to do some action when a user interacts with that element. Or they might do something more complex, such as writing the code for a database-driven application that handles creating, reading, updating, and deleting (CRUD) tasks
For web developers and designers, a simple example of boilerplate code that can be automated is the basic structure of an HTML page. Every valid HTML page starts with a document type declaration followed by an HTML element, and then a head element (including several internal elements, such as the title and meta tags), and then a body element.
Letting AI write the template
You can minimize the work required to generate a simple HTML template in many ways, such as by using a code snippet or searching the web for an example. How ever, if you want to create a custom boilerplate that includes some structure and gives you a good start on the design of a future website, you could simply ask your AI. For example, I gave ChatGPT the following request:
Crafting CRUD with AI
One of the most common tasks in any computer program is accessing a data source and writing functions for performing operations with the data source. The basic operations you can do with any data source are creating a record, reading a record, updating a record, and deleting a record. The collective name for the code that makes these operations possible is the wonderfully evocative acronym CRUD. Most people don’t enjoy writing CRUD.
In this section, you use generative AI to reduce the amount of work it takes to generate some CRUD. To get started with this exercise, you need to have access to an interface for chatting with a generative AI model such as ChatGPT, Google Bard, or Microsoft Bing. If you don’t have an account with any of these services yet, follow the instructions in Chapter 4 to sign up for ChatGPT.
Then, once you have a chat window in front of you, start with a short request to the generative model to see what it will do. If the service you’re using won’t or can’t fulfill your request, you won’t have wasted much time crafting a detailed prompt. For example, when I asked Bing to generate CRUD, it started to, but then told me to ask something else, as shown in Figure 1-2
Now determine whether the response shows any promise. If you didn’t get a response, try using a different generative AI model.
Here is the beginning of the response I got to my initial prompt (“Write JavaScript functions for performing CRUD operations for a database table named todo-list.”) from ChatGPT using the GPT-3.5 model:
The response is adequate, but because I failed to provide enough information about my desired application, ChatGPT used an array as if it were a database, which is unlikely to be what is needed here.
If you get a promising response to your initial prompt, give the model additional details. For example, my next step would be to tell ChatGPT that this is a Node.js application that will be working with a MongoDB database and that it should use Mongoose
The process of refining your instructions to a GenAI model and providing context and examples is called prompt engineering. Chapter 4 covers the process of prompt engineering in detail. Figure 1-3 shows my second prompt.
This time, ChatGPT responded with a complete Node.js application that connects to a local database and can perform CRUD operations. Listing 1-1 shows the regen erated code.
Helping with Syntax
A large part of the work involved in computer programming is simply remember ing or looking up the rules that define the structure of a programming language, also known as its syntax. Each language or code library has its own way of doing things. Once you know the basics of how a programming language works (such as how to create a function, use basic operators, and write loops), you need to know what built-in functions are available in your environment (whether it’s a browser or a mobile operating system) and what parameters and types of data they expect to receive. That’s a lot to remember, and no programmer I’ve ever met can remember everything there is to remember about one programming language, much less several programming languages. With the help of GenAI tools, you can have instant access to the collected knowledge of millions of coders.
You may be asking yourself at this point, “But is it ethical for AI to harvest everyone’s code like that?” This topic is hotly debated and the subject of at least one lawsuit. I explore legal and ethical issues having to do with GenAI throughout this book.
Stop remembering trivial details
When I teach programming, my students often ask me questions about syntax and application programming interfaces (APIs) rather than how something works. When I get a question about syntax, I answer the question if I can without looking it up; otherwise, I encourage students to “Google it.” With time and experience, remembering syntax just starts to happen.
When writing software, one of the best skills is knowing how and where to look for answers. And most of the time, the best place is through a search engine. Because search engines employ machine learning to determine the best results to show in response to queries, we’ve been using AI for coding for some time now
Hinting at code mastery
One of the oldest forms of computer-assisted coding is code completion. Microsoft introduced its implementation of code completion, IntelliSense, in Visual Studio in 1996. These types of tools work by suggesting functions and methods that partially match something you’ve started typing, as shown in Figure 1-6. Traditional code completion functionality doesn’t employ GenAI, and its suggestions can often be frustratingly incorrect. However, if you need help with the syntax or spelling (or don’t want to type the full names of functions), code completion is useful.
Generative AI takes code completion to the next level by offering suggestions based on its training. When integrated into your IDE, tools such as GitHub’s Copilot or Amazon’s CodeWhisperer can suggest entire statements or functions, rather than just single function calls
GenAI models trained on large datasets of code can offer multiple suggestions based on what other programmers have written; libraries, classes, and functions you’ve imported into the current file; and even other files that are open in your IDE or in your code repository
Adapting to new syntax
Like code hint features in IDEs, GenAI can help you learn or remember the syntax for functions or methods. For example, Copilot will give you hints as you type; you can ignore these by continuing to type or accept them by pressing tab
For example, I have trouble remembering the order of the arguments to pass to the Array.reduce method. Figure 1-9 shows a Copilot hint for starting the method
You can also use GenAI chat interfaces to learn about new syntax. However, keep in mind that the model you’re using may have been trained on data that predates the existence of the function or method you’re seeking help with. For example, GPT-3’s training data cutoff date is September 2021, so the model has no knowl edge of events or technologies developed after that date. Figure 1-10 shows what happened when I asked GPT-3 about a feature of JavaScript introduced in 2022.
GPT-4, on the other hand, has a more recent training data cutoff and can also search the web. Figure 1-11 shows ChatGPT’s response to the same question but with the model set to GPT-4.
Also remember that, in response to a query, a GenAI model may just invent some thing that sounds plausible but is incorrect. ChatGPT’s tendency to make up facts and people is legendary. However, in cases where something is as rule-based as a computer language, it usually gets the facts right. As a rule, have a certain amount of distrust of any AI-generated code. Always verify.
Figure 1-12 shows ChatGPT 3.5’s response to my question about a non-existent JavaScript method
Linting with AI
Linters are tools that flag programming errors, bugs, and style issues. The techni cal name for the job that linters do is static code analysis. The static part of static code analysis refers to the fact that these tools check the code without compiling or running it. Using a linter can help you improve the quality of your code
Since most GenAI tools are (at the time of this writing) incapable of compiling and running the code you write, anytime you prompt a machine learning model to look for errors or bad style in your code, you’re using it as a linter
Detecting bad code with static code analysis
To use an AI chatbot as a linter, you can prompt the model with your code and ask it what’s wrong with it. Since GenAI models have been trained on a large quantity of working code, they’re generally pretty good at finding typos, inconsistencies, and code that doesn’t look right.
Simply write something like “What’s wrong with this code?” and then paste in the code that’s not working. Figure 1-13 shows Google Bard’s response to my question about a function with several typos and examples of bad coding style.
Integrating AI with static code analysis
Because programming languages have strict rules, linters don’t necessarily need to use AI to detect bad code. However, linting tools that make use of AI can provide functionality that’s not possible with standard code linters, such as
Detailed natural language explanations of what’s wrong with your code
Defining new rules using natural language
Fixing problematic code or refactoring problematic code or both
Many linters that aren’t AI-enhanced can automatically fix certain kinds of prob lems with your code, and defining new rules generally isn’t difficult. The potential for providing detailed descriptions as well as improving your code is promising.
Several tools add AI to existing linters. For example, eslint-ai (available at https://github.com/iamando/eslint-ai) is an open-source project that uses GPT-3 to enhance the errors returned by the most popular JavaScript linter, ESLint.
Using eslint-ai requires you to have an account and an API key from OpenAI, and using the tool may result in OpenAI charges. However, GitHub Copilot and other tools include features for cleaning, fixing, and improving your code as part of their standard subscriptions. Chapter 7 covers linting and debugging with AI in detail
No comments:
Post a Comment