Reader small image

You're reading from  Refactoring with C#

Product typeBook
Published inNov 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781835089989
Edition1st Edition
Languages
Right arrow
Author (1)
Matt Eland
Matt Eland
author image
Matt Eland

Matt Eland is a Microsoft MVP in Artificial Intelligence (AI) who has been working with .NET since 2001. Matt has served as a senior engineer, software engineering manager, and .NET programming instructor. He is currently an AI specialist and senior consultant at Leading EDJE near Columbus, Ohio, where he helps companies with their software engineering and data science needs using C# and related technologies. Matt speaks and writes in his community and co-organizes the Central Ohio .NET Developers Group while pursuing a master's degree in data analytics.
Read more about Matt Eland

Right arrow

AI-Assisted Refactoring with GitHub Copilot

Change is a constant in technology, and that’s certainly true in the .NET ecosystem. Every year, Microsoft releases a new version of .NET and C# packed with new features to keep the language exciting, useful, and relevant as technology changes. But perhaps the most significant changes to .NET development in the last two years have come not from the major language releases, but in the field of artificial intelligence through AI agents such as GitHub Copilot and ChatGPT.

In this chapter, we’ll explore how GitHub Copilot integrates into Visual Studio and brings ChatGPT-like conversational AI into your editor. We’ll also explore some of the interesting possibilities this opens and some of the things we must keep in mind when considering whether this new technology has a place in our toolset.

We’ll cover the following topics in this chapter:

  • Introducing GitHub Copilot
  • Getting started with GitHub Copilot...

Technical requirements

The starting code for this chapter is available from GitHub at https://github.com/PacktPublishing/Refactoring-with-CSharp in the Chapter11/Ch11BeginningCode folder.

Introducing GitHub Copilot

In 2021, GitHub announced a new artificial intelligence tool called GitHub Copilot. GitHub Copilot is an editor extension that integrates into different editors including JetBrains Rider, VS Code, and all editions of Visual Studio 2022.

What GitHub Copilot does is it looks at the code you just typed and generates predictions for the code it thinks you’re about to type. If it has a prediction and you are not currently typing, GitHub Copilot displays the prediction in grey text in front of your cursor for you to evaluate and possibly add to your code, as shown in Figure 11.1:

Figure 11.1 – GitHub Copilot suggesting code to add as the developer types

Figure 11.1 – GitHub Copilot suggesting code to add as the developer types

Copilot does this by using a predictive machine learning model that has been trained on various pieces of code in many different programming languages, including C#, F#, JavaScript, and SQL.

Understanding GitHub’s predictive model

If this sounds familiar...

Getting started with GitHub Copilot in Visual Studio

In order to work with GitHub Copilot, you’ll need to have a GitHub account. If you don’t have one, you can sign up for a free GitHub account at https://github.com/signup.

GitHub Copilot also requires that you work with Visual Studio 2022 version 17.4.4 or later. If you haven’t installed Visual Studio, you can download a copy at https://visualstudio.microsoft.com/downloads/.

If you need to update or check your Visual Studio version, a quick way of doing either task is to launch the Visual Studio Installer from the Windows menu. This will let you see your current version and optionally update your edition of Visual Studio, as shown in Figure 11.5:

Figure 11.5 – Updating Visual Studio from the Visual Studio Installer

Figure 11.5 – Updating Visual Studio from the Visual Studio Installer

Once you have a GitHub account and an up-to-date edition of Visual Studio, you can install the GitHub Copilot extension.

Installing and activating GitHub...

Refactoring with GitHub Copilot Chat

Because GitHub Copilot Chat was trained on open-source repositories, it has had a lot of exposure to people writing about code. Because of this, its likelihood of being able to provide helpful insight is high.

To see this, we’ll refactor the aptly-named RefactorMe.cs file, which looks like this:

namespace Packt.CloudySkiesAir.Chapter11;
public class RefactorMe {
  public void DisplayRandomNumbers() {
    List<int> numbers = new List<int>();
    for (int i = 1; i <= 10; i++) {
      Random rand = new Random();
      int n = rand.Next(1, 101);
      numbers.Add(n);
    }
    String output = string.Join(", ", numbers.ToArray());
    Console.WriteLine(output);
  }
}

This code has some deliberate inefficiencies...

Drafting documentation with GitHub Copilot Chat

Over the years, I’ve learned that developers don’t always like to document their code. While some code truly is self-documenting as developers claim, other areas require proper documentation.

In C#, we document public methods with XML documentation, such as the sample comment for the DisplayRandomNumbers method:

/// <summary>
/// Displays a sequence of 10 random numbers.
/// </summary>
public void DisplayRandomNumbers() {

This specially formatted comment is interpreted by Visual Studio to display additional help in the editor. This extra information appears in the editor when you are trying to invoke your method, as shown in Figure 11.12:

Figure 11.12 – Visual Studio showing a tooltip containing the method comment

Figure 11.12 – Visual Studio showing a tooltip containing the method comment

Although the sample documentation we saw a moment ago was relatively straightforward, documentation gets a bit more complex when you have return values...

Generating test stubs with GitHub Copilot Chat

For our final technical section of this chapter, let’s look at a method that finds the largest number in a sequence of numbers, provided that the number doesn’t have a “7” in it somewhere, such as a 71 or 17. This method is located inside of TestMe.cs:

public static class TestMe {
  public static int CalculateLargestNumberWithoutASeven(
    INumberProvider provider) {
    IEnumerable<int> numbers = provider.GenerateNumbers();
    return numbers.Where(x => !x.ToString().Contains("7"))
                  .Max();
  }
}

This CalculateLargestNumberWithoutASeven method takes in an INumberProvider that allows us to call GenerateNumbers and get a sequence of integers.

Next, the method looks at the resulting sequence, finds...

Understanding the limits of GitHub Copilot

By this point in the chapter, many readers are probably thinking “This is great, but can I actually use this in my job?” That’s a valid question, so let’s talk about the two common objections: privacy of source code and license concerns with public code.

Data privacy and GitHub Copilot

Many organizations considering GitHub Copilot are concerned that integrating an AI tool into their code editor means exposing their code to GitHub. Some also raise the potential that GitHub might even use the organization’s private code to generate new large language models in the future where these new models might generate code based on the organization’s proprietary logic.

These are valid concerns, and depending on which edition of GitHub Copilot you are using, there may be some basis for them.

With GitHub Copilot for Individuals, the prompts you send to GitHub Copilot, including surrounding code and Copilot...

Case study: Cloudy Skies Airline

The use of AI at Cloudy Skies Airlines started first with individual developers, as often happens with productivity tools and new technologies. James, an eager young developer on the team, shared with his coworkers how he’s been trying GitHub Copilot, feeling more capable and empowered, and even learning new things. His coworkers were excited, but his manager, Mya, had a few concerns.

Looping in the chief technology officer (CTO), Mya and James demonstrated the capabilities of the tool and talked about how it worked. The CTO was worried about legal compliance and the safety of the company’s intellectual property. As a result, the use of Copilot and other AI tools was temporarily suspended while the team investigated the implications of the technology.

After some research, and with the help of the GitHub Copilot Trust Center, the Cloudy Skies Airlines team agreed to a multi-stage plan:

  1. Pilot the program: A small group of developers...

Summary

In this chapter, we saw how GitHub Copilot and GitHub Copilot Chat can help developers understand, refactor, document, and even test their code.

We talked about how GitHub Copilot is not an intelligent AI overlord, but instead a predictive model built around patterns in text found in open-source repositories. As a result, the code it generates may not even compile and may contain security vulnerabilities, bugs, performance issues, or other undesirable effects.

We closed this chapter with a discussion of privacy and open-source licensing that organizations must care about for security and compliance purposes and how GitHub Copilot helps organizations meet those needs.

In the next chapter, we’ll explore code analysis in Visual Studio and see how code analysis can help you detect potential issues and targets for refactoring in your code.

Questions

  1. How do GitHub Copilot and GitHub Copilot Chat work?
  2. How can you address data privacy and compliance concerns with Copilot?

Further reading

You can find more information about GitHub Copilot at these URLs:

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Refactoring with C#
Published in: Nov 2023Publisher: PacktISBN-13: 9781835089989
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Matt Eland

Matt Eland is a Microsoft MVP in Artificial Intelligence (AI) who has been working with .NET since 2001. Matt has served as a senior engineer, software engineering manager, and .NET programming instructor. He is currently an AI specialist and senior consultant at Leading EDJE near Columbus, Ohio, where he helps companies with their software engineering and data science needs using C# and related technologies. Matt speaks and writes in his community and co-organizes the Central Ohio .NET Developers Group while pursuing a master's degree in data analytics.
Read more about Matt Eland