Master Github Copilot

Master Github Copilot

Is AI Pair Programming the Future?

ยท

9 min read

Featured on Hashnode

download.jpg A few weeks ago Github announced a state-of-the-art, AI based pair programmer beta extension for VSCode which shook considerably the software development industry. While many were concerned this AI tool will take our jobs this is definitely not the case yet. This past month I've been testing Github Copilot in many projects mainly JS and both on the frontend, backend and also for other more uncanny tasks.

1. How It Works

Once you have registered for the beta programme you will get a notification you are eligible to test the extension and gain access to it via the VSCode Extension Marketplace after that you are pretty much good to go. Now whenever we write some code the extension will give a suggestion on how to complete the line in a light gray tint and we can press Tab to accept it.

image.png

Another way to use the extension is by writing comments and having the GPT-3 powered mammoth hog your resources to generate a common interview question solution such as how to invert a binary tree๐Ÿ˜‹.

image.png

But what if we don't like the suggestion, by pressing CTRL + Enter a tab with 10 complete suggestions (not one liners) appears on the right side.

image.png

It's incredible how fast you are able to generate lines of code to solve simple tasks such as fundamental algorithms or even more specialised tasks.

2. What It Can Do

We saw in the previous examples that it's pretty great at responding to interview questions hopefully making them obsolete in the future since I still haven't reversed a linked-list nor inverted a tree in production.

Answer interview questions & solve simple algorithms

Let's test it with some LeetCode (an amazing platform for learning algorithms and getting ready for interviews) questions such as

Merge two sorted lists (Easy)

// Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.
var mergeTwoLists = function(l1, l2) {
    var head = new ListNode(0);
    var p = head;
    while (l1 !== null && l2 !== null) {
        if (l1.val < l2.val) {
            p.next = l1;
            l1 = l1.next;
        } else {
            p.next = l2;
            l2 = l2.next;
        }
        p = p.next;
    }
    if (l1 === null) {
        p.next = l2;
    }
    if (l2 === null) {
        p.next = l1;
    }
    return head.next;
};

Add two numbers (Medium)

// You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
// You may assume the two numbers do not contain any leading zero, except the number 0 itself.
var addTwoNumbers = function(l1, l2) {
  let result = new ListNode(0);
  let current = result;
  let carry = 0;
  while (l1 || l2 || carry) {
    let val = 0;
    if (l1) {
      val += l1.val;
      l1 = l1.next;
    }
    if (l2) {
      val += l2.val;
      l2 = l2.next;
    }
    val += carry;
    carry = val >= 10 ? 1 : 0;
    val %= 10;
    current.next = new ListNode(val);
    current = current.next;
  }
  return result.next;
};

For hard difficulty questions the copilot doesn't always hit the homerun but it does give some decent suggestions.

We can say Github Copilot is great at algorithms

Complete parantheses

This may seem pretty hilarious but one use-case I found copilot really good at is at adding the final parantheses and brackets for map functions in JSX. Everyone loves React and all but the amount of brackets you have to handle some times is awful.

Who would have though we would have an AI save us from bracket hell ๐Ÿ‘ฟ.

image.png

We can say Github Copilot is acceptable at ending lines

Create API endpoints

One thing to note is that Github Copilot like other AI powered tools for code autocompletion (Tabnine & Kite) benefits from a larger codebase as it learns from it.

If we want a brand new server in GO, (I always promised myself to learn this incredibly performance and future proof language) we get this suggestion:

// simple API server in GO
package main

import (
    "fmt"
    "log"
    "net/http"
    "strings"
)

func main() {
    http.HandleFunc("/", handler)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hello, %q", strings.TrimPrefix(r.URL.Path, "/"))
}

I have no idea about GO yet but this looks like a good start for a simple server.

Let's try this on a Realworld implementation using NestJS and Prisma as ORM.

image.png

Copilot know to use a deleteAll method from TagService (although it doesn't exist). Let's see if it suggest it if we go to TagService.ts

image.png

Not really but still a valid guess.

We can say Github Copilot is decent at backend

Generate Values

I want to create an array with all states of the US to use in a dropdown. I'm very bad at geography and not native to the US and our AI friend comes to the rescue:

// array with all countries of US
var countries = ["Alabama", "Alaska", "Arizona", "Arkansas", "California", "Colorado",
  "Connecticut", "Delaware", "Florida", "Georgia", "Hawaii", "Idaho", "Illinois",
  "Indiana", "Iowa", "Kansas", "Kentucky", "Louisiana", "Maine", "Maryland",
  "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana",
  "Nebraska", "Nevada", "New Hampshire", "New Jersey", "New Mexico", "New York",
  "North Carolina", "North Dakota", "Ohio", "Oklahoma", "Oregon", "Pennsylvania",
  "Rhode Island", "South Carolina", "South Dakota", "Tennessee", "Texas", "Utah",
  "Vermont", "Virginia", "Washington", "West Virginia", "Wisconsin", "Wyoming"
];

Honestly I have no idea if those are correct or not which is a general downside of Github Copilot as it doesn't validate whether the code works or not or it's source.

I have to write some placeholder values for a list of place cards since the API endpoint isn't ready yet:

// array of points of interest with name, address and rating
var pois = [
  {name: "White House", address: "1600 Pennsylvania Ave", rating: 5},
  {name: "Eiffel Tower", address: "The Eiffel Tower is located in Paris, France", rating: 5},
  {name: "Statue of Liberty", address: "Statue of Liberty, New York City, New York, United States", rating: 5},
  {name: "Pentagon", address: "The Pentagon is in Washington, D.C., United States", rating: 5},
  {name: "World Trade Center", address: "World Trade Center, New York, New York, United States", rating: 5},
  {name: "Pentagon", address: "The Pentagon is in Washington, D.C., United States", rating: 5},
  {name: "World Trade Center", address: "World Trade Center, New York, New York, United States", rating: 5},
  {name: "Statue of Liberty", address: "Statue of Liberty, New York City, New York, United States", rating: 5},
  {name: "Eiffel Tower", address: "The Eiffel Tower is located in Paris, France", rating: 5},
  {name: "White House", address: "1600 Pennsylvania Ave", rating: 5},
  {name: "Pentagon", address: "The Pentagon is in Washington, D.C., United States", rating: 5},
  {name: "World Trade Center", address: "World Trade Center, New York, New York, United States", rating: 5},
  {name: "Statue of Liberty", address: "Statue of Liberty, New York City, New York, United States", rating: 5},
  {name: "White House", address: "1600 Pennsylvania Ave", rating: 5},
  {name: "Eiffel Tower", address: "The Eiffel Tower is located in Paris, France", rating: 5},
  {name: "Pentagon", address: "The Pentagon is in Washington, D.C., United States", rating: 5},
  {name: "World Trade Center", address: "World Trade Center, New York, New York, United States", rating: 5}
]

We can say Github Copilot is decent at generating values

Generate SQL

SQL is really tedious to write and designing a database sometimes requires a bit of imagination, what if we ask Github Copilot to design a database for a CryptoTrading platform since AI and blockchain should become friends as the top technologies of 2021.

-- Create a table for a CryptoCurrency
CREATE TABLE IF NOT EXISTS CryptoCurrency (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    symbol TEXT NOT NULL,
    rank INTEGER NOT NULL,
    price_usd FLOAT NOT NULL,
    price_btc FLOAT NOT NULL,
    volume_24h_usd FLOAT NOT NULL,
    market_cap_usd FLOAT NOT NULL,
    available_supply FLOAT NOT NULL,
    total_supply FLOAT NOT NULL,
    max_supply FLOAT NOT NULL,
    percent_change_1h FLOAT NOT NULL,
    percent_change_24h FLOAT NOT NULL,
    percent_change_7d FLOAT NOT NULL,
    last_updated INTEGER NOT NULL,
    FOREIGN KEY (last_updated) REFERENCES TimeStamp(id)
);

This is a great first suggestion from Github Copilot. What if we ask him to add a Wallet and User tables to see if it uses a foreign key with the previous code.

-- Create User and CryptoWallet tables
CREATE TABLE IF NOT EXISTS User (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    username TEXT NOT NULL,
    password TEXT NOT NULL,
    FOREIGN KEY (id) REFERENCES TimeStamp(id)
);
CREATE TABLE IF NOT EXISTS CryptoWallet (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    currency_id INTEGER NOT NULL,
    amount FLOAT NOT NULL,
    FOREIGN KEY (user_id) REFERENCES User(id),
    FOREIGN KEY (currency_id) REFERENCES CryptoCurrency(id)
);
-- Create a table for a User's transactions
CREATE TABLE IF NOT EXISTS UserTransactions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    transaction_type TEXT NOT NULL,
    transaction_datetime INTEGER NOT NULL,
    transaction_amount FLOAT NOT NULL,
    transaction_currency TEXT NOT NULL,
    transaction_address TEXT NOT NULL,
    transaction_status TEXT NOT NULL,
    FOREIGN KEY (user_id) REFERENCES User(id),
    FOREIGN KEY (transaction_currency) REFERENCES CryptoCurrency(name)
);
-- Create a table for a User's balances
CREATE TABLE IF NOT EXISTS UserBalances (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    balance_datetime INTEGER NOT NULL,
    total_balance FLOAT NOT NULL,
    FOREIGN KEY (user_id) REFERENCES User(id)
);
-- Create a table for a User's transactions
CREATE TABLE IF NOT EXISTS UserTransactions (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    user_id INTEGER NOT NULL,
    transaction_type TEXT NOT NULL,
    transaction_datetime INTEGER NOT NULL,
    transaction_amount FLOAT NOT NULL,
    transaction_currency TEXT NOT NULL,

Although it's not finished it's an unbelievable amount of decently well designed fields in a crazy short span of time.

We can say Github Copilot is great at simple SQL

Write 'good' copy

What if we want to write a blog post everyday and we are really really bad or slow at writing.

image.png

We can say Github Copilot is not great at Blogging

Damn this AI is really narcissistic but unfortunately not great at writing markdown, but it's not at all what it was designed to do.

image.png

3. Should You Use It

In my opinion Github Copilot is a great tool to add to your productivity workflow although is far from complete and requires some performance improvements.

Many consider AI to be the bane of developer existence but it's a long way until that even becomes a possibility, in the years to come even if AI becomes more and more competent at writing code this will not cause our jobs to become extinct but to evolve and change.

Right now it's nothing more that a glorified autocompletion tool with extra 'StackOverflow integration' capabilities so there's nothing to worry about.

My final advice is to use it as a fun tool not to depend on it, also there may be some legal issues due to the AI being trained on all public repositories no matter the license which is a rather sensible topic, so using it for production may be undesirable for the long term.

I hope you enjoyed this tutorial of what Github Copilot can do and would love if you put a ๐Ÿ’œ on it!

ย