How I Use GitHub Copilot as a Developer

Ahmet Özokutan
5 min readJun 3, 2024

--

Yazının Türkçe versiyonu için lütfen buraya tıklayın.

The world of software development is constantly evolving, and as developers, we need to keep up with these changes. When I first heard about GitHub Copilot, I wondered how this tool could transform my coding process. Throughout my use, I noticed how Copilot contributed to my software development workflows, and I want to share these experiences.

What is GitHub Copilot?

GitHub Copilot is an AI-powered code assistant developed by GitHub, OpenAI, and Microsoft. It integrates with popular code editors like Visual Studio Code and predicts your code, offering suggestions as you type. Copilot is trained on a vast database of code, enabling it to provide suggestions in various programming languages and frameworks. It works with languages like C#, Python, JavaScript, TypeScript, Ruby, Go, and more.

Copilot analyzes the code you write and predicts the rest of it. For example, when you start writing a function, Copilot understands its purpose and offers suggestions to complete it. These suggestions are based on millions of lines of previously written and analyzed code.

The suggestions appear in real-time, without interrupting your coding flow, allowing you to work quickly and smoothly. You can choose from the suggestions or continue writing your own code. Copilot learns your style and preferences, making more accurate suggestions over time. It also automatically adds comments and documentation lines to your code, making it more understandable and easier to maintain.

Benefits of Using Copilot

  1. Faster Coding: GitHub Copilot significantly increases coding speed. The suggested code blocks save time, especially for repetitive tasks.
  2. Exploring New Technologies: Copilot helps you discover new libraries and APIs. It speeds up your learning process by suggesting functions and methods you might not be aware of.
  3. Reducing Errors: It lowers the likelihood of making mistakes while coding. This is particularly helpful for complex and lengthy code blocks, preventing errors in syntax and logic.

My Experience with GitHub Copilot

Rapid Prototyping

When starting a new project, I can quickly create a prototype thanks to Copilot. The suggested code snippets help me set up the basic structure swiftly. During this process, I also get the chance to discover libraries and technologies I haven’t tried before.

Code Reviews and Optimization

During code reviews, I use Copilot’s suggestions to write cleaner and more optimized code. This improves the overall code quality of the team. For example, I implement Copilot’s suggestions to enhance the performance of a function, which helps me apply optimizations I might have overlooked initially.

Documentation and Code Clarity

While coding, the comments and documentation lines suggested by Copilot make the code more understandable. This benefits both myself and my team members by making the code easier to comprehend. Copilot’s explanations are particularly useful when working on complex algorithms and data structures.

How GitHub Copilot Improves My Coding Efficiency

Using GitHub Copilot Chat has brought even more efficiency to my workflow. Here are some specific examples from ASP.NET Core projects:

/explain: Explaining Selected Code

GitHub Copilot Chat is a great tool for explaining selected code snippets. For instance, if you have a complex algorithm and need to understand how it works, you can use this command. It provides a clear and concise explanation of what the code does.

[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginViewModel model)
{
if (!ModelState.IsValid)
{
return BadRequest("Invalid login attempt.");
}

var user = await _userManager.FindByNameAsync(model.Username);
if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
{
var roles = await _userManager.GetRolesAsync(user);
var token = GenerateJwtToken(user, roles);
return Ok(new { Token = token });
}

return Unauthorized("Invalid login attempt.");
}

private string GenerateJwtToken(IdentityUser user, IList<string> roles)
{
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
};

claims.AddRange(roles.Select(role => new Claim(ClaimsIdentity.DefaultRoleClaimType, role)));

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var token = new JwtSecurityToken(_configuration["Jwt:Issuer"],
_configuration["Jwt:Issuer"],
claims,
expires: DateTime.Now.AddMinutes(30),
signingCredentials: creds);

return new JwtSecurityTokenHandler().WriteToken(token);
}

/fix: Proposing Fixes for Problems

When there is an issue in your code, this command offers solutions. It is very useful during debugging. For example, you can get suggestions for performance issues or logical errors. This command helps you quickly fix and optimize your code.

Copilot Prompt : Fix any potential security issues in the following login method by improving the JWT token generation process and adding additional checks.

/doc: Generating Documentation

You can use this command to document your code. Lack of documentation in large projects can cause serious issues. This command helps you create detailed documentation for your functions and classes, making your code easier to maintain and understand.

/// <summary>
/// Handles user login functionality and generates JWT token based on user roles.
/// </summary>
/// <param name="model">Login view model containing user credentials.</param>
/// <returns>Returns a JWT token if login is successful; otherwise, returns an error message.</returns>
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginViewModel model)
{
if (!ModelState.IsValid)
{
return BadRequest("Invalid login attempt.");
}

var user = await _userManager.FindByNameAsync(model.Username);
if (user != null && await _userManager.CheckPasswordAsync(user, model.Password))
{
if (!user.EmailConfirmed)
{
return Unauthorized("Email not confirmed.");
}

var roles = await _userManager.GetRolesAsync(user);
var token = GenerateJwtToken(user, roles);
return Ok(new { Token = token });
}

return Unauthorized("Invalid login attempt.");
}

/// <summary>
/// Generates a JWT token based on user information and roles.
/// </summary>
/// <param name="user">IdentityUser object containing user information.</param>
/// <param name="roles">List of roles associated with the user.</param>
/// <returns>Returns a JWT token string.</returns>
private string GenerateJwtToken(IdentityUser user, IList<string> roles)
{
var claims = new List<Claim>
{
new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Email, user.Email)
};

claims.AddRange(roles.Select(role => new Claim(ClaimsIdentity.DefaultRoleClaimType, role)));

var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var token = new JwtSecurityToken(
issuer: _configuration["Jwt:Issuer"],
audience: _configuration["Jwt:Issuer"],
claims: claims,
notBefore: DateTime.UtcNow,
expires: DateTime.UtcNow.AddMinutes(30),
signingCredentials: creds);

return new JwtSecurityTokenHandler().WriteToken(token);
}

Conclusion

GitHub Copilot is a powerful tool for software developers. It speeds up the coding process while reducing the chances of errors and aiding in learning new technologies. Using Copilot effectively can increase your productivity and help you complete projects faster. In the future, I am eager to see how Copilot and similar AI tools will transform our software development processes.

References

*The code examples in this article are generated by AI and are not directly related to any real projects.

--

--