The grand irony of my role here at Stack Overflow is that I work to create great content for developers, but am absolutely hopeless when it comes to programming on my own. Over my four years here, I’ve gained a pretty good understanding of software at the macro level. I can have an intelligent discussion about the value of microservices vs monoliths, strongly typed languages, cloud vs on-prem, or large language models. But asking me to whip up a simple CRUD app is a recipe for disappointment.
[Note to readers: before leaving a comment about someone with no skills wasting your time, refer back to the title and remember that you can’t insult a person who has already completed a perfect self-own.]
Anyway, over the last month, I decided to try diving back in, inspired by a steady stream of posts I saw on social media that showed people writing natural language instructions that today’s AI assistants can transform into working code. Maybe, I thought, my basic understanding of how a web app gets built will allow me to engineer the right prompts, and the AI can handle writing and debugging the actual code.
The app I had in mind is fairly simple: people can list let others know when they are going to be at the local dog park. After some discussion, I found that this is a basic CRUD app:
Normally, to get started, I would brush up on my paltry HTML skills and prepare a sacrifice to the JavaScript gods, but, in 2023, I can just ask an AI:
I want to build a single page web app that will allow users to submit their name, their dog's name, and the time they intend to visit the local dog park. After users submit this information, it is displayed for anyone who visits the page. I need front end code and a database on the backend that can store state. First - Please explain how you would create this app using pseudo-code examples. Second - write the code for this app and share it as a single code snippet.First, let me outline the general structure and pseudo-code for the app.Frontend (HTML, CSS, JavaScript)a. Create an HTML form for user input (user's name, dog's name, and intended visit time)b. Style the form using CSSc. Add JavaScript to handle form submission and send data to the backend APIBackend (Node.js with Express and a database like MongoDB)a. Set up a Node.js server with Expressb. Create API endpoints to handle data submission and retrievalc. Connect to a MongoDB database to store and fetch the submitted dataConnect frontend and backenda. Use JavaScript to send data from the frontend to the backend APIb. Display the fetched data on the frontend
Ok, let’s drop the code it generated into my WordPress CMS just to take a peek and…by George, it works. Looks a little janky, though. Let’s clean things up.
Edit the code above so that the three text fields are centered on the page and there are three line breaks between the name and time fields.
And just like that: Sure, here’s the updated code with the changes you requested:
Looks better, but it’s still missing something. I know!
Modify the code above so that an ASCII image of a dog appears over the text fields for name and time. The ASCII image of the dog is centered on the page.
How sweet it is. This is what mean when they say AI is a tool to unlock human creativity and potential, not to replace us.
So far so good, but the input doesn’t persist. I need some kind of backend to record my state.
I want to add a database to the code above so that I can store the state of the output and display all text submitted to users on the client side. I want the database to contain two rows, one for "name" and one for "time". When users submit a "name" and "time" the database stores this state and it's displayed in the output section. The database clears these rows once a day at midnight Eastern time.
A few seconds later the AI spits back a code block that uses jQuery and PHP with a MySQL database. For a hopeless programmer like me, it’s fascinating to see that I’ve now got access to building blocks in multiple languages. I can’t even master one on my own!
That said, the AI can’t solve the issue of ME being an intractable vortex of bugs and errors, attracting obstacles to functioning code like a magnet picks up nails. I go through the process of setting up an AWS account and following the online tutorial for creating a MySQL database, but can’t actually get it to connect to the workbench.
The AI tries to be kind. I ask it to rewrite the code for a NoSQL database and it helpfully switches from PHP to Node.JS without missing a beat. I spin up a MongoDB Atlas cluster, but am lost again in a sea of error messages.
Eventually I try a clean slate. I start a new dialog with the AI and ask it to create a simple app that will work with Firebase. I’ve learned a few things from my first two attempts, so I understand a little better how the pieces are supposed to fit together. It’s easier for me to work in the terminal and to have a clean file and folder structure. At 9:30pm on a random Tuesday, I’ve got a functioning CRUD app—input your info about your next visit to the dog park, refresh the page and there it is for the world to see.
You can accuse me of talking my book, but in all honesty, there were some things the AI simply couldn’t solve for. It insisted I needed the code below:
<!-- The core Firebase JS SDK is always required and must be listed first --> <script src=“https://www.gstatic.com/firebasejs/9.6.8/firebase-app.js”></script> <!-- Add Firestore (database) --> <script src=“https://www.gstatic.com/firebasejs/9.6.8/firebase-firestore.js”></script>
But it didn’t connect that to an error I kept getting:
Uncaught SyntaxError: Unexpected token 'export'
A quick web search and I found the following question and answer pair. Do I understand why deleting that code fixed the issue? Of course not. But it let me get closer to a working solution.
The AI had a bunch of ideas about how to solve for this one:
Uncaught SyntaxError: Cannot use import statement outside a module
I tried three or four of its solutions, but we got nowhere. But the web had what I needed. I fed the context of the answer back in and voila, a working web app.
Index.html:
```
``` App.js:
// Initialize Firebaseconst firebaseConfig = { apiKey: "MYAPIKey", authDomain: "coolest-dogpark-scheduler.firebase.com", projectId: "Bens Awesome Project Goes Here", storageBucket: "Ben's Bucket", messagingSenderId: "NUMBERS", appId: "LOTTA CHARACTERS"};// Initialize Firestore (Database)const app = firebase.initializeApp(firebaseConfig);const db = firebase.firestore(app);// Form and data displayconst form = document.getElementById('data-form');const dataDisplay = document.getElementById('data-display');// Handle form submissionform.addEventListener('submit', async (event) => { event.preventDefault(); const name = document.getElementById('name').value; const dogName = document.getElementById('dog-name').value; const time = document.getElementById('time').value; const timestamp = firebase.firestore.Timestamp.now(); await db.collection('data').add({ name, dogName, time, timestamp }); // Clear form form.reset(); location.reload();});// Fetch data and displayasync function fetchData() { const today = new Date(); today.setHours(0, 0, 0, 0); const querySnapshot = await db.collection('data') .where('timestamp', '>=', firebase.firestore.Timestamp.fromDate(today)) .get(); dataDisplay.innerHTML = ''; querySnapshot.forEach(doc => { const data = doc.data(); dataDisplay.innerHTML += `<p>${data.name} - ${data.dogName} - ${data.time}</p>`; });}// Call fetchData() initially and whenever the form is submittedfetchData();form.addEventListener('submit', fetchData);
Lots of folks are making claims about AI replacing programmers, but for the time being, the effect on my usage was the opposite. The AI was the inspiration to try coding again; it was a springboard that got me going and handled some basics. But it wasn’t enough to get me to the finish line on its own. When things started to get tricky, I was pinging colleagues in chat for help, or searching up error messages and sifting through answers from Stack Overflow, technical documentation, and blog tutorials.
What do you call something that can string together complex concepts and provide useful answers to questions about everything from history to poetry to programming? A friend of mine suggested “thought calculator” and I’ve fallen in love with this phrase. It perfectly captures this new technology’s power, and its limitations.
The AI isn’t sentient or autonomous, as far as we know, but it has a form of intelligence which you can leverage as a tool. Coding is one of its best applications, because it uses textual instructions to produce an objective output. We can argue forever about the quality of an AI’s marketing copy or literary essay, but with programming, setting aside for a moment the important question of code quality, we can test to see if it produces the desired result.
As our CEO announced last week, we’re thinking about ways we can use the power of generative AI to continue building a knowledge community that is open and accessible to all. Some folks protested that it would be wrong for us to train AI on Stack Overflow data, but the reality is lots of people are already doing that. We could sit around and do nothing while other organizations ingest the web into an algorithmic black box, or we could try to build a system where human input is still recognized and rewarded, where the output created by the collaboration of a human and their thought calculator is something everyone can then leverage and learn from.
If you’ve been experimenting with AI to help you write code, let us know what you think in the comments. I’ll try to be back in a week or two with an update, once my army of autonomous agents completes my plan for world domination.
The post The worst coder in the world tries an AI sidekick appeared first on Stack Overflow Blog.