Your profile

One profile for every MSDEVBUILD site. Only you can see it, and the site owner if you write in.

Lesson 23 of 30
❮Prev Next❯

Generate, Refactor and Document Code with GitHub Copilot

Module 5: Productivity ⏱ 10 min read Updated

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    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.

    Simulate it » No Azure account needed

    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.

    VS Code & GitHub: Generate, refactor and document code Refactor a loop, review the diff and add docs.
    </> Embed

    Embed this simulation

    Free for trainers, teachers and bloggers. Paste this into your page:

    Loading…

    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
    1. Select the function and ask in Edit mode for a refactor that keeps the behaviour. Say what must not change.
    2. Review the diff: removed lines in red, added in green. Run the tests before you Keep.
    3. /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.

    😟 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
    🛠️ Solved with: Generate, refactor, document

    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:

    1. Have tests for the code you’re about to change. If there aren’t any, ask Copilot for some first.
    2. Select the code and open chat in Edit mode (or inline chat for a single spot).
    3. Say what must not change: “Refactor cartTotal to use reduce and keep the behaviour the same.”
    4. Read the diff. Removed lines show in red, added in green.
    5. 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

    • /doc on 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:

    AskUse
    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

    Online retail

    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.
    Ready for more?The full lesson adds the technical explanation, when to use it, interview questions and revision notes.

    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.

    Question 1

    Question 1 of 5

    A developer wants GitHub Copilot to rewrite a loop in a function as a call to reduce. The function's behavior must not change, and the developer wants to review the proposed changes before they are applied. What should the developer do?

    Question 2

    Question 2 of 5

    A developer needs to add documentation comments that describe the parameters and return value of a selected function. Which GitHub Copilot Chat slash command should the developer use?

    Question 3

    Question 3 of 5 · Select 2

    A new team member must understand an unfamiliar repository quickly and wants to avoid switching between Visual Studio Code, search engines and internal wikis. Which TWO GitHub Copilot Chat features should the team member use?

    Question 4

    Question 4 of 5

    A developer types a descriptive comment above an empty function and pauses. GitHub Copilot shows gray text that implements the function. Which key accepts the entire suggestion?

    Question 5

    Question 5 of 5

    A team uses GitHub Copilot to refactor modules. After a refactor is merged, a rarely used report produces incorrect results. The refactored module had no automated tests. What should the team do first to prevent this problem in future refactors?

    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. 1.Which slash command writes documentation comments?Show

      /doc

    2. 2.Which chat mode applies changes to files and shows diffs to Keep or Undo?Show

      Edit mode.

    3. 3.What should you do before choosing Keep on a refactor?Show

      Review the diff and run the tests.

    4. 4.Which participant asks questions about the whole workspace?Show

      @workspace

    5. 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

    Studying with a friend? Send them this lesson

    It's free and needs no sign-up. Their progress saves in their own browser.

    Lesson done? Make it stick with a quick gameSort It, Match the Pairs, Lightning Round and Who Am I? Earn XP and badges. Play ❯

    Install MSDEVBUILD Azure

    Free · no account · works offline

    Save the whole course for offline ›

    Hi, I’m your Nimbus

    Your study buddy. Pick what we do next.

    MSDEVBUILD · Multi-Stack Dev Build

    Sign in to MSDEVBUILD

    One account for Azure certifications and the blog: sign in here and you are signed in on both. Your XP, streak, practice deck and certificate stay in sync on every device. Optional: everything works without an account.