Generate, Refactor and Document Code with GitHub Copilot
30-second answer
Copilot speeds up three everyday jobs. Generate: describe what you want in a comment or a chat prompt and accept the inline suggestion or code block. Refactor: select code and ask, usually in Edit mode, for a change that keeps the behaviour the same; review the diff, run the tests, then Keep or Undo. Document: /doc writes doc comments, and chat can draft README sections or explain a file. It also cuts context switching: /explain, @workspace and #codebase answer questions about unfamiliar code inside the IDE instead of a browser search. Every result is a draft you review and test.
Exam objective: 5.1.1 Use Copilot for code generation, refactoring, and documentation. 5.1.2 Accelerate learning and reduce context switching. (Skills measured as of August 7, 2026)
Simulations
Feel it before you read it. No account needed, nothing leaves this page.
Select the function and ask in <strong>Edit</strong> mode for a <strong>refactor</strong> that keeps the behaviour. Say what must not change.
👆 Click the glowing item on screen to continue
Read the steps as text
- Select the function and ask in Edit mode for a refactor that keeps the behaviour. Say what must not change.
- Review the diff: removed lines in red, added in green. Run the tests before you Keep.
- /doc writes documentation comments. Copilot can also draft a README section, explain a regex, or summarise a file you’ve never seen, so you spend less time switching to search.
🧪 Simulation for learning. Screens are simplified versions of Visual Studio Code and github.com with GitHub Copilot; names, files and suggestions are examples. Not affiliated with GitHub or Microsoft, and nothing here touches your real account.
🖱️ Drag to rotate · scroll or pinch to zoom
Edit mode (Copilot Edits)
Edit applies changes to the files you choose, across several files at once. You see each diff and Keep or Undo it.
🤔 What happens if…
Read this tour as text
- Ask mode. Ask answers questions about code and concepts and can suggest code blocks. It doesn’t change your files by itself.
- Edit mode (Copilot Edits). Edit applies changes to the files you choose, across several files at once. You see each diff and Keep or Undo it.
- Agent mode. Agent works out which files to touch, edits them, runs commands and tests, reads errors and keeps going until the task is done. It asks before running terminal commands unless you’ve approved them.
- MCP servers add tools. The Model Context Protocol (MCP) lets Copilot use external tools: the GitHub MCP server, a browser, a docs search or your own API. Configure servers in
.vscode/mcp.json(VS Code) or with/mcp(CLI). Organizations can restrict which servers are allowed. - Sessions and sub-agents. Long tasks fill the context window. Agent sessions keep work separate, and a sub-agent can do a side task in its own context and hand back only a summary.
- Copilot coding agent. Assign an issue to Copilot on github.com (or
/delegatefrom the CLI). The coding agent works in a GitHub Actions environment on its own branch and opens a draft pull request with its changes. - Review stays human. You review the agent’s PR like any other. Copilot code review can comment and suggest changes, but its review doesn’t count as an approval. A person merges.
- Copilot CLI. The same agent in the terminal:
copilotfor a session with slash commands,copilot -p "…"for one prompt, and--allow-tool/--deny-toolto control what it may run.
Use Copilot the way a careful developer would: write tests first, let the edge cases expose the bug, ask for the smallest fix, and prove it with a green run before you commit.
🎓 Education-only simulation. Your lab is saved in this browser, so you can leave and continue later.
😟 THE PROBLEM
A 200-line function nobody wants to touch, with no comments.
😊 THE SOLUTION
Let Copilot refactor it in small steps and document it, while tests keep you safe.
- Tangled code✓ Edit mode refactors
- No docs✓ /doc and README drafts
- Searching for answers✓ Ask about the code in place
Start with a question
How much of your coding day is actually writing new logic, and how much is tidying, explaining and documenting?
For most developers, less than half is new logic. The rest is renaming, untangling loops, writing doc comments nobody wants to write, and searching for “what does this function even do”.
That’s where Copilot earns its place. On the contoso-shop team, Ravi needed to clean up cartTotal. He selected the loop, asked Copilot in Edit mode to “use reduce and keep the behaviour the same”, read the red and green diff, ran npm test, and pressed Keep. Then /doc wrote the JSDoc. Five minutes, and he never opened a browser tab.
Explain it like I’m 10
The technical explanation
Generate code
Copilot generates code in two main ways:
- Inline suggestions. Write a comment or a function signature, pause, and ghost text appears. Tab accepts, Esc dismisses, Alt+] / Alt+[ (Option on macOS) cycle alternatives, Ctrl+→ accepts one word at a time.
- Chat. Ask in the Chat view (Ctrl+Alt+I) or inline chat (Ctrl+I) and insert the code block you want. Agent mode can create whole files and wire them up.
// Return the cart total in paise, rounded, after applying the discount code
export function cartTotalPaise(items, code) {
// Copilot suggests the body here as ghost text
}
A precise comment is a prompt. “Return the total in paise, rounded” gets better code than “calculate total”.
Refactor without changing behaviour
A refactor changes structure, not behaviour. The safe loop:
- Have tests for the code you’re about to change. If there aren’t any, ask Copilot for some first.
- Select the code and open chat in Edit mode (or inline chat for a single spot).
- Say what must not change: “Refactor cartTotal to use reduce and keep the behaviour the same.”
- Read the diff. Removed lines show in red, added in green.
- Run the tests, then Keep or Undo.
// before
let total = 0;
for (const i of items) total += i.price * i.qty;
// after (Copilot Edits)
const total = items.reduce((sum, i) => sum + i.price * i.qty, 0);
Good refactor prompts are specific: extract a function, rename a variable everywhere, replace callbacks with async/await, split a long file. After you make one change, next edit suggestions (NES) can predict the related edit further down the file, which suits repetitive renames.
Document code
/docon a selection writes doc comments (JSDoc, docstrings, XML comments depending on the language).- Chat can draft a README section, a usage example, or a changelog entry from a diff.
- On github.com, the Copilot button in a pull request description drafts a PR summary.
Read generated docs as carefully as code. Copilot describes what the code looks like it does, and if the code has a bug, the docs will cheerfully describe the bug as intended.
Learn faster, switch less
The exam groups “accelerate learning and reduce context switching” with this topic. Inside the IDE you can:
| Ask | Use |
|---|---|
| What does this code do? | Select it, /explain |
| Where is X handled in this repo? | @workspace or #codebase |
| How do I do Y in this framework? | Ask chat with the relevant file attached |
| What does this error mean? | #terminalLastCommand or @terminal |
| What’s open in this repo’s issues? | @github |
Each answer saves a trip to a search engine or a wiki, and keeps your focus on the code. Confirm the answers that matter by reading the code yourself; Copilot can be confidently wrong.
Architect level Ask, Edit or Agent for a refactor?
Ask suggests code you copy in yourself, fine for learning or a tiny change. Edit applies changes to the files you pick and shows each diff, the usual choice for a refactor you want to control. Agent decides which files to touch, edits them, can run the tests after you approve the command, and iterates on failures. Use agent mode for wider changes such as “rename this field across the API, the UI and the tests”, and keep the request small enough that you can still review every diff.
Real-world business scenario
Contoso (fictional)
- The problem
- contoso-shop had grown fast. Functions were long, half had no comments, and new joiners spent their first two weeks asking 'where does this happen?' in team chat.
- What they used
- Copilot Chat in VS Code: /explain and @workspace for onboarding, Edit mode refactors with a tests-first rule, /doc for comments, and Copilot PR summaries on github.com.
- Why that choice
- Answers came inside the editor, refactors stayed small and reviewable as diffs, and docs were written while the code was fresh.
- The result
- New joiners shipped their first pull request in their first week, and the team cleared a backlog of 'add comments' tickets in one sprint.
When to use it and when not to
✓ Use it when…
- Boilerplate and well-understood code from a clear comment or signature.
- Small, focused refactors with tests in place and a diff you can read.
- Doc comments, README drafts and explanations of unfamiliar code.
✕ Think twice when…
- Large refactors with no tests. You can't tell whether behaviour changed.
- Accepting generated docs or code without reading them.
↔ Alternatives to consider
- IDE refactoring tools (Rename Symbol, Extract Method) for purely mechanical changes that must be exact.
- Copilot coding agent for a well-described refactor you want delivered as a draft pull request.
Test yourself with exercises
5 original practice questions in the GH-300 style. Pick your answers, then check them. You will see why each option is right or wrong. Score 75% or more and this topic is marked complete.
Interview preparation
Say your answer out loud first, then open the model answer. Interviewers care more about your reasoning than the exact words.
Beginner How do you get Copilot to generate a function?
Model answer
I write a clear comment or function signature saying what it does, its inputs and output, and pause. Copilot suggests the body as ghost text and I press Tab if it's right. For anything bigger, I ask in chat and review the code block before inserting it.
Interviewer follows up
Do you accept it straight away?
You
No. I read it, check it handles the edge cases I care about, and run the tests. It's a draft from a model, not tested code.
Intermediate How do you refactor safely with Copilot?
Model answer
I make sure there are tests first. Then I select the code and ask in Edit mode for the specific refactor, saying the behaviour must stay the same. I read the diff line by line, run the tests, and only then choose Keep. Small refactors, one at a time, are much easier to review.
Experienced developer You've joined a team with a large unfamiliar codebase. How does Copilot help you get productive?
Model answer
I ask @workspace or use #codebase for "where is the discount logic and how is it called", /explain on the files I need to change, and ask for a summary of the folder structure. That keeps me in the editor instead of hopping between search, wikis and chat. I still confirm the important answers by reading the code.
Scenario Copilot's refactor passes review but breaks a rarely used report. What went wrong in the process?
Model answer
The refactor changed behaviour and nothing caught it. Either there were no tests around that path or nobody ran them before Keep. I'd add a test for the report, ask for smaller refactors with "keep behaviour identical", and make CI run the suite on every pull request.
Quick revision
Key points
- Generate: comments, signatures or chat prompts; accept with Tab or insert from chat.
- Refactor: select the code, use Edit mode, say the behaviour must not change, review the diff, run tests, Keep or Undo.
- Document: /doc for doc comments; chat can draft README sections and explain code.
- /explain, @workspace and #codebase answer questions inside the IDE, reducing context switching.
- Next edit suggestions (NES) predict the next edit after a change, handy for repetitive refactors.
- Everything Copilot produces is a draft you review and test.
Important terminology
- Refactoring
- Changing the structure of code to make it clearer or easier to maintain without changing what it does.
- Edit mode (Copilot Edits)
- A Copilot Chat mode that applies changes to the files you choose and shows each diff for you to Keep or Undo.
- /doc
- A Copilot Chat slash command that generates documentation comments for the selected code.
- /explain
- A Copilot Chat slash command that explains the selected code or the active file in plain language.
- Context switching
- Leaving your editor to search docs, forums or other tools, which breaks focus. Asking Copilot in the IDE reduces it.
Common mistakes
- Refactoring without tests, so a behaviour change goes unnoticed.
- Accepting a large multi-file edit without reading the diff.
- Trusting generated docs that describe what the code should do rather than what it does.
Exam tips
- "Restructure code without changing behaviour" = refactor, review the diff and run tests.
- "Generate documentation comments" = /doc. "Understand unfamiliar code" = /explain.
- "Reduce time spent searching outside the editor" = ask Copilot Chat in the IDE (context switching).
Five quick revision questions
-
1.Which slash command writes documentation comments?Show
/doc
-
2.Which chat mode applies changes to files and shows diffs to Keep or Undo?Show
Edit mode.
-
3.What should you do before choosing Keep on a refactor?Show
Review the diff and run the tests.
-
4.Which participant asks questions about the whole workspace?Show
@workspace
-
5.What does reducing context switching mean here?Show
Getting answers inside the IDE instead of leaving for search or docs.
Official references
Finished this lesson? Tick it off. Your progress is saved in this browser.
Next up: Sample Data and Modernizing Legacy Code
Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges.