Module 3.1: GenAI for Developers — Code Generation, Debugging, and Documentation

YOUR PROGRESS — GENERATIVE AI: ZERO TO JOB-READY ← Course home
8 of 20 modules complete
GENERATIVE AI: ZERO TO JOB-READY  ›  UNIT 3  ›  MODULE 1 OF 4

GenAI for Developers — Code Generation, Debugging, and Documentation

⏱ 15 min read 📝 Assignment inside Hands-on examples

Welcome to Unit 3. You now have the prompt engineering skills from Unit 2. This unit is about applying those skills to your actual work — starting with the role most of you are entering or preparing for: software development.

This module is not theoretical. Every technique here maps to a task you will encounter in your first week at TCS, Infosys, Wipro, HCL, or any Indian IT company — or in your current academic projects if you are still in college.


Why AI is now a baseline skill for developers

55%
faster task completion by developers using GitHub Copilot — tested across 4,800 developers
46%
of all code written by active Copilot users is now AI-generated — up from 27% in 2022
84%
of developers use or plan to use AI tools in 2026 — up from 76% the previous year

At Infosys, 28 million lines of code were generated using AI tools in FY26. At Accenture, teams using Copilot saw pull request time drop from 9.6 days to 2.4 days — a 4x acceleration. Code review turnaround improved by 67%.

This is not a future prediction. It is the current working environment at every major Indian IT company. Developers who use AI tools effectively are completing the same work in half the time. Those who do not are working twice as hard to keep up.

The critical nuance: Only 29–46% of developers trust AI-generated code without review. The fastest developers are not the ones who accept AI output blindly — they are the ones who use AI to generate a solid first draft, then review and refine quickly. This review skill is what this module teaches.

Use case 1 — Code generation

Writing new code from scratch

The most common developer use case. Give the AI enough context about your stack, constraints, and requirements and it will produce a working first draft in seconds. The key is specificity — the more precisely you describe what you need, the less cleanup you do afterwards.

EXAMPLE — Django REST API endpoint for Indian fintech
You are a senior Django developer building a fintech REST API.

Write a Django REST Framework view for a loan eligibility check endpoint.

Requirements:

  • Endpoint: POST /api/v1/loan/check/
  • Input: JSON with fields: user_id (int), monthly_income (float), existing_emi (float), requested_amount (float), tenure_months (int)
  • Logic: Debt-to-income ratio check — if (existing_emi + proposed_emi) > 40% of monthly_income, reject
  • Proposed EMI formula: P * r * (1+r)^n / ((1+r)^n - 1) where r = 0.01 (1% monthly rate)
  • Output: JSON with fields: eligible (bool), reason (str), max_eligible_amount (float)
  • Error handling: validate all input fields, return 400 for missing/invalid data
  • Include serializer and URL config

Stack: Django 4.2, DRF 3.15, Python 3.11

What makes this prompt work: Specific stack versions, exact field names, the business logic written out explicitly (DTI ratio, EMI formula), error handling requirements, and output format defined. The model produces working, production-ready code — not a skeleton that needs rewriting.
Claude Sonnet — best for complex logic ChatGPT — good, strong DRF knowledge GitHub Copilot — best in-editor, weaker for full features

For simpler functions — utility methods, data transformations, standard CRUD operations — GitHub Copilot inside VS Code is the fastest tool. It auto-completes as you type, with no prompt needed. For complex features like the one above, Claude or ChatGPT with a detailed prompt is more reliable.


Use case 2 — Debugging

🐞
Finding and fixing bugs

Debugging is where AI saves the most time for junior developers. A bug that takes 45 minutes to trace manually often takes under 2 minutes with AI — if you provide enough context. The three things that matter: the error message, the code, and what you expected to happen.

EXAMPLE — Python KeyError debugging
I am getting a KeyError in my Django view. Here is the error traceback and the relevant code:

Error: KeyError at /api/v1/portfolio/summary/ ’total_invested' File “/app/views/portfolio.py”, line 47, in get_portfolio_summary return Response({‘invested’: data[’total_invested’]})

My code (views/portfolio.py, lines 40-55): def get_portfolio_summary(request): user_id = request.user.id holdings = StockHolding.objects.filter(user_id=user_id) data = {} for holding in holdings: data[’total_value’] = data.get(’total_value’, 0) + holding.current_value data[’total_invested’] = data.get(’total_invested’, 0) + holding.purchase_price serializer = PortfolioSerializer(data) return Response({‘invested’: data[’total_invested’]})

Expected: Return the total invested amount for the user. Actual: KeyError on ’total_invested’ even though I set it in the loop.

Identify the bug, explain why it occurs, and provide the fix.

What makes this prompt work: Full traceback, exact line reference, the relevant code block, expected vs actual behaviour. The model can immediately identify that data['total_invested'] fails when holdings is an empty queryset (the loop never runs). Without the code and context, it would guess.
TEMPLATE — Universal debugging prompt
I am debugging a [language/framework] issue.

Error message: [paste exact error or traceback]

Relevant code: [paste the function or section where the error occurs]

Context:

  • What I expected to happen: [describe]
  • What actually happens: [describe]
  • What I have already tried: [list any attempted fixes]

Stack: [language version, framework version, relevant libraries]

Identify the bug, explain why it occurs, and provide the corrected code.

Save this template in your AI Learning Journal. It works for any language — Python, Java, JavaScript, C++. The "what I have already tried" section prevents the model from suggesting things you have already ruled out.
Claude Sonnet — lowest hallucination on code ChatGPT — fast, strong on common frameworks GitHub Copilot Chat — works in-editor on open files

Use case 3 — Code review and improvement

🔍
Reviewing existing code for quality and issues

In Indian IT service delivery, code review is a core part of every sprint. AI can act as a first-pass reviewer — catching issues before a senior engineer reviews it. This reduces review cycles, improves your code quality, and signals professionalism to your team lead.

EXAMPLE — Pre-review self-check
You are a senior software engineer reviewing code before it goes to production at an Indian IT services company.

Review this Python function and check for the following — respond in this exact format:

  1. BUGS: List any logic errors or exceptions that could occur in production
  2. PERFORMANCE: Identify any inefficiencies (N+1 queries, unnecessary loops, memory issues)
  3. SECURITY: Flag any security concerns (SQL injection, hardcoded secrets, unsafe inputs)
  4. READABILITY: Note any naming, structure, or documentation issues
  5. VERDICT: Pass / Needs changes — with one-line summary

Code to review: def get_user_transactions(user_email): conn = sqlite3.connect(’transactions.db’) cursor = conn.cursor() query = “SELECT * FROM transactions WHERE email = ‘” + user_email + “’” cursor.execute(query) results = cursor.fetchall() return results

The structured output format is critical here. Without specifying the exact sections, the model gives a prose review that is hard to act on. With this format, you get a checklist you can work through systematically. The model will correctly flag the SQL injection vulnerability in the + string concatenation.
Claude Sonnet — most thorough code review ChatGPT — fast, catches common issues well

Use case 4 — Writing tests

Generating unit tests and test cases

Test writing is the task developers hate most and AI handles best. Given a function, the model can generate unit tests covering normal cases, edge cases, and error conditions in seconds. At Wipro, 60+ GenAI use cases exist for software testing alone.

EXAMPLE — pytest unit tests for a validation function
You are a senior QA engineer writing pytest unit tests.

Write comprehensive unit tests for this Python function:

def validate_pan_number(pan: str) -> dict: “““Validates Indian PAN card number format. Format: 5 letters + 4 digits + 1 letter (e.g., ABCDE1234F) Returns: {‘valid’: bool, ’error’: str or None} "”” import re if not pan: return {‘valid’: False, ’error’: ‘PAN number is required’} pan = pan.upper().strip() pattern = r’^[A-Z]{5}[0-9]{4}[A-Z]{1}$’ if re.match(pattern, pan): return {‘valid’: True, ’error’: None} return {‘valid’: False, ’error’: ‘Invalid PAN format’}

Cover these test categories:

  1. Valid PAN numbers (at least 3 examples)
  2. Invalid format cases (wrong length, wrong pattern, special characters)
  3. Edge cases (empty string, None, whitespace, lowercase input)
  4. Boundary cases (numbers where letters expected, vice versa)

Use pytest. Use descriptive test function names. Include docstrings on each test.

India-specific context matters here. PAN validation is a real task in every Indian fintech and HR system. By using a domain-relevant example, you get tests that are immediately usable — not generic tests you have to adapt. The explicit test categories prevent the model from writing 5 similar valid cases and missing all the edge cases.
Claude Sonnet — best test coverage, fewest missing cases ChatGPT — good for common testing frameworks GitHub Copilot — autocomplete only, no coverage planning

Use case 5 — Writing documentation

📄
Docstrings, README files, API documentation

Documentation is the task that almost never gets done properly and AI does extremely well. A well-prompted model will generate docstrings, README files, and API documentation that are consistent, complete, and formatted correctly — saving hours of work per sprint.

EXAMPLE — Docstring generation
Generate a comprehensive Google-style docstring for this Python function.

Include: summary line, Args section with types and descriptions, Returns section with type and description, Raises section for all possible exceptions, and one usage Example.

def calculate_sip_returns(monthly_investment: float, annual_rate: float, years: int) -> dict: months = years * 12 monthly_rate = annual_rate / 100 / 12 if monthly_rate == 0: total_value = monthly_investment * months else: total_value = monthly_investment * ( ((1 + monthly_rate) ** months - 1) / monthly_rate ) * (1 + monthly_rate) total_invested = monthly_investment * months total_returns = total_value - total_invested return { ’total_invested’: round(total_invested, 2), ’total_value’: round(total_value, 2), ’total_returns’: round(total_returns, 2), ‘return_percentage’: round((total_returns / total_invested) * 100, 2) }

Specify the docstring format explicitly — Google style, NumPy style, or reStructuredText. Each looks different. If your team uses a specific format, say so. The SIP (Systematic Investment Plan) context makes this immediately relevant to Indian fintech work.
EXAMPLE — README generation for a GitHub project
Write a professional README.md for my GitHub project.

Project: A FastAPI backend for an Indian stock portfolio tracker Stack: Python 3.11, FastAPI, PostgreSQL, Redis, Docker Features: User authentication (JWT), portfolio CRUD, real-time NSE price updates via WebSocket, profit/loss calculation, tax liability estimation (LTCG/STCG)

Include these sections in order:

  1. Project title and one-line description
  2. Features list (bullet points)
  3. Tech stack table
  4. Prerequisites
  5. Installation steps (numbered, Docker-first approach)
  6. API endpoints table (method, endpoint, description, auth required)
  7. Environment variables table
  8. Contributing guide (2–3 sentences)
  9. Licence (MIT)

Use GitHub Markdown formatting. Keep language professional but not corporate.

A well-written README dramatically improves your GitHub profile for placements. Recruiters at TCS, Infosys, and product companies specifically look at GitHub README quality as a signal of professional communication skills. This prompt produces a complete README in 30 seconds.
Claude Sonnet — most natural writing, least AI-sounding ChatGPT — good for technical docs and READMEs

The AI-assisted development workflow

Here is how the best developers at Indian IT companies structure their AI usage — not using it for everything, but using it at the right points in the workflow:

RECOMMENDED WORKFLOW — AI-ASSISTED DEVELOPMENT
1
Understand the requirement first, manually. Before touching AI, read the ticket/story and make sure you understand the business logic. AI cannot understand requirements it has not seen.
2
Use GitHub Copilot for boilerplate and standard patterns. CRUD operations, serializers, standard middleware, common utility functions — let Copilot autocomplete in the editor. Accept or reject each suggestion.
3
Use Claude or ChatGPT for complex logic. Business rules, algorithms, non-standard implementations — write a detailed prompt with context, stack, constraints, and expected output. Review the generated code thoroughly before using it.
4
Use AI for the first pass of tests. After writing your feature, prompt Claude to generate tests covering normal, edge, and error cases. Add any domain-specific cases the model missed. Never skip manual review of tests.
5
Use AI for pre-review self-check. Before submitting for code review, run your code through the structured review prompt above. Fix what it finds. Your senior engineer will notice the improvement.
6
Use AI for documentation last. Once the code is finalised, generate docstrings, README updates, and API documentation. Documentation generated after finalisation is more accurate than documentation generated during development.

What to never do with AI-generated code

Three absolute rules for professional AI code use:

1. Never commit AI-generated code without reading every line. The 88% retention rate means 12% of Copilot suggestions contain errors. In a 500-line feature, that is 60 lines that need fixing. Blindly committing AI code is how bugs reach production.

2. Never use AI-generated code involving security, authentication, or financial calculations without a senior review. The SQL injection example above would pass a casual review. Security vulnerabilities in AI-generated code are one of the fastest-growing categories of production incidents in 2026.

3. Never paste client code or proprietary business logic into a consumer AI tool (ChatGPT free, Claude free). Use your company's approved enterprise AI tool for anything confidential. If no enterprise tool is available, describe the problem abstractly without pasting actual client code.

The three things to remember

KEY TAKEAWAYS — MODULE 3.1
  1. AI generates a first draft, not a final product — 46% of code is AI-generated but 12% of suggestions contain errors. The skill is fast, accurate review — not blind acceptance. Read every line before committing.
  2. Specificity is the difference between useful and generic code — include your exact stack versions, field names, business logic, error handling requirements, and output format in every code generation prompt. Vague prompts produce skeleton code you have to rewrite anyway.
  3. Use the right tool for the right task — Copilot for in-editor boilerplate, Claude for complex logic and thorough code review, ChatGPT for documentation and general-purpose tasks. No single tool is best at everything.

Assignment 3.1 — Apply AI to a Real Development Task

This assignment builds your prompt library for development work. Each task should take 15–20 minutes.

  1. Code generation: Pick a function or feature you need to write for a current project, assignment, or practice problem. Write a detailed prompt using the six-component structure. Include your exact stack, requirements, and constraints. Test the output and note what you had to fix.
  2. Debugging: Take a bug you are currently stuck on (or have been stuck on recently). Use the universal debugging template from this module. Paste the error, code, and context. Note how long it would have taken you to find this manually versus with AI.
  3. Code review: Take any function you have written in the past week — assignment, project, or practice code. Run it through the structured review prompt. Note what the model finds that you did not catch yourself.
  4. Save all three prompts in your AI Learning Journal under "Module 3.1 — Developer Prompts." These form the start of your developer prompt library, which you will build out in Module 3.4.

After this assignment you will have concrete evidence of what AI can and cannot do for your development work — calibrated to your actual stack, not a generic tutorial example.

Sources and data references
ClaimSource
Developers complete tasks 55% faster with GitHub Copilot — tested with 4,800 developersQuantumrun / companieshistory.com GitHub Copilot Statistics 2026
GitHub Copilot generates 46% of all code written by active users; 88% code retention rateaboutchromebooks.com / getpanto.ai GitHub Copilot Statistics Jan 2026
84% of developers use or plan to use AI tools in 2026index.dev Developer Productivity Statistics with AI Tools 2026
Only 29–46% of developers trust AI-generated code without review; 46–68% report quality issuesindex.dev Developer Productivity Statistics with AI Tools 2026
Accenture: pull request time dropped from 9.6 to 2.4 days; 67% reduction in code review turnaroundwearetenet.com GitHub Copilot Usage Data Statistics 2025
Infosys 28 million lines of AI-generated codeInfosys FY26 earnings commentary
Wipro 60+ GenAI use cases for software testingWipro 6-K SEC filing FY2025