Loading…

The worst coder in the world tries an AI sidekick

Look out, world! The worst coder is back and ready to create code he doesn't understand.

Article hero image

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:

  • Create: a web form where users can input the name of their dog and the time they plan to arrive at the park.
  • Read: Other users can see who is planning to visit and what time they’ll be there.
  • Update: I’m not even trying to get this fancy! Also, no take-backsies!
  • Delete: At the end of each day, the database deletes all entries so the slate is blank for the following morning.

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 CSS
c. Add JavaScript to handle form submission and send data to the backend API
Backend (Node.js with Express and a database like MongoDB)
a. Set up a Node.js server with Express
b. Create API endpoints to handle data submission and retrieval
c. Connect to a MongoDB database to store and fetch the submitted data
Connect frontend and backend
a. Use JavaScript to send data from the frontend to the backend API
b. 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.

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dog Park App</title>
    <style>
        /* Add your CSS styles here */
    </style>
</head>
<body>
    <h1>Dog Park App</h1>
    <form id="dog-park-form">
        <input type="text" id="userName" placeholder="Your name" required>
        <input type="text" id="dogName" placeholder="Dog's name" required>
        <input type="time" id="visitTime" required>
        <button type="submit">Submit</button>
    </form>
    <ul id="visitors-list"></ul>
    <script>
        // Add your JavaScript code here
    </script>
</body>
</html>

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, the changes are made. I'll spare you that code snippet as it's largely the same. 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.
<!DOCTYPE html>
<html>
<head>
	<title>My Webpage</title>
	<script>
		// This function clears the text area every 24 hours at midnight
		function clearText() {
			var currentTime = new Date();
			var hours = currentTime.getHours();
			var minutes = currentTime.getMinutes();
			var seconds = currentTime.getSeconds();
			if (hours == 0 && minutes == 0 && seconds == 0) {
				document.getElementById("output").value = "";
			}
		}
	</script>
	<style>
		/* This style centers the text fields and the dog image on the page */
		.container {
			display: flex;
			flex-direction: column;
			align-items: center;
		}
		input[type="text"], textarea {
			display: block;
			margin: 0 auto;
		}
		.ascii-dog {
			font-size: 50px;
			text-align: center;
			margin-bottom: 50px;
		}
	</style>
</head>
<body onload="setInterval('clearText()', 1000);">
	<div class="container">
		<div class="ascii-dog">
			<pre>
  __      _
o'')}____//
 \"''''''''\\
   \        \
    )________\
    |_|_|_|_|_|    
			</pre>
		</div>
		<label for="name">Name:</label><br>
		<input type="text" id="name"><br><br><br>
		<label for="time">Time:</label><br>
		<input type="text" id="time"><br><br><br>
		<button onclick="displayText()">Submit</button><br>
		<label for="output">Output:</label><br>
		<textarea id="output" rows="5" cols="50" readonly></textarea>
	</div>
	<script>
		// This function displays the text from the input fields in the output area
		function displayText() {
			var name = document.getElementById("name").value;
			var time = document.getElementById("time").value;
			var output = document.getElementById("output");
			output.value += name + " - " + time + "\n";
		}
	</script>
</body>
</html>

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. (Ed. note - removing this code fixed the error, but caused an issue with the window refreshing when a user clicked the submit button. I later added it back in, and got refresh working, and didn't encounter the error a second time.)

The AI also 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:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Palatine Bark Play Scheduler</title>
  <style>
    * {
      box-sizing: border-box;
    }
    .banner {
      background-color: #4CAF50;
      color: white;
      text-align: center;
      padding: 1rem;
      margin-bottom: 1rem;
    }
    .container {
      display: flex;
      justify-content: space-around;
      flex-wrap: wrap;
    }
    form {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 1rem;
      width: 50%;
    }
    .data-section {
      width: 50%;
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    .data-container {
      width: 100%;
      padding: 1rem;
      text-align: center;
    }
    img {
      max-width: 100%;
      height: auto;
      margin: 2rem 0;
    }
    /* Media query for smaller screens */
    @media screen and (max-width: 767px) {
      form, .data-section {
        width: 100%;
      }
    }
  </style>
</head>
<body>
  <div class="banner">
    <h1>Palatine Bark Play Scheduler</h1>
  </div>
  
  <div class="container">
    <form id="data-form">
      <label for="name">Your Name:</label>
      <input type="text" id="name" required>
      
      <label for="dog-name">Your Dog's Name:</label>
      <input type="text" id="dog-name" required>
      
      <label for="time">Time:</label>
      <input type="time" id="time" required>
      
      <button type="submit">Submit</button>
      <img src="https://firebasestorage.googleapis.com/v0/b/palatine-bark.appspot.com/o/good%20boy.png?alt=media&token=XXXXXXXX" alt="Good Boi" />
    </form>
    <div class="data-section">
      <h2>Today's Data</h2>
      <div class="data-container">
        <div id="data-display"></div>
      </div>
    </div>
  </div>
<!-- Firebase App (the core Firebase SDK) -->
<script src="https://www.gstatic.com/firebasejs/9.6.8/firebase-app-compat.js"></script>
<!-- Firebase Firestore -->
<script src="https://www.gstatic.com/firebasejs/9.6.8/firebase-firestore-compat.js"></script>
<!-- Your custom JavaScript file -->
<script type="module" src="app.js"></script>
</body>
</html>

App.js:

// Initialize Firebase
const 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 display
const form = document.getElementById('data-form');
const dataDisplay = document.getElementById('data-display');

// Handle form submission
form.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 display
async 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 submitted
fetchData();
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.

We are all in the process of figuring out how to use these new tools in a safe and ethical manner. We would love to hear from the community about how you're approaching the issue. 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.

Login with your stackoverflow.com account to take part in the discussion.