Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ The `github-copilot-features-status` folder shows the main features of GitHub Co

The `github-copilot-features` folder contains example files and data to demonstrate different functionalities and features:

- `advanced-refactor` - Advanced code refactoring scenarios for complex systems
- `agent` - Example of using agent mode in github copilot
- `api-integration` - Examples of integrating with various APIs using GitHub Copilot
- `change-format` - Example of converting data between different formats
- `change-language` - Examples of converting code between different programming languages
- `code-refactor` - Examples of GitHub API client implementations and code refactoring
Expand All @@ -29,6 +31,7 @@ The `github-copilot-features` folder contains example files and data to demonstr
- `notebook` - Examples of data analysis using Jupyter notebooks
- `refactor` - Various code examples requiring refactoring
- `reusable-prompts` - Examples of reusable prompts in github copilot
- `security-best-practices` - Security best practices implementation with GitHub Copilot
- `translation` - translate document using github copilot
- `unit-test` - Examples of unit tests using github copilot
- `vision` - Examples of vision usage in github copilot
Expand All @@ -39,7 +42,7 @@ The `github-copilot-features` folder contains example files and data to demonstr
The `github-copilot-scenario-roles` folder contains use cases in different scenarios:
- `common-scenario` - use github copilot in common scenario
- `infrastructure-as-code` - use github copilot to compose infrastructure script
- `talk-to-database` - GitHub Copilot use cases in sql script generation with mcp
- `talk-to-database` - GitHub Copilot use cases in SQL script generation and database interaction patterns with mcp
- `ui-automation` - GitHub Copilot use cases in UI automation script generation
- `ui-design-dalle` - GitHub Copilot use cases in image generation automatically using dalle 3
- `ui-design-figma` - GitHub Copilot use cases in html generation with figma design
Expand Down
64 changes: 64 additions & 0 deletions github-copilot-features/advanced-refactor/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Advanced Refactoring with GitHub Copilot

This directory contains examples of complex code that can benefit from advanced refactoring patterns with GitHub Copilot's assistance.

## Lab Objectives

- Learn how to identify and refactor code with multiple code smells and anti-patterns
- Use GitHub Copilot to suggest modern architecture patterns and best practices
- Transform legacy code into maintainable, testable, and scalable solutions

## Exercises

### 1. Legacy Service Refactoring

The `legacy_service.js` file represents a typical legacy service with several issues:

- Global state and side effects
- Callback-based asynchronous code
- Repetitive code blocks and tight coupling
- Lack of proper error handling
- No separation of concerns

**Challenge:** Use GitHub Copilot to refactor this code to:
- Implement proper dependency injection
- Use modern async/await patterns
- Create appropriate class/module structure
- Add proper error handling
- Make the code more testable

### 2. Complex Algorithm Optimization

The `complex_algorithm.py` file contains an inefficient implementation of a data processing algorithm.

**Challenge:** Use GitHub Copilot to:
- Optimize the algorithm for better performance
- Reduce memory usage
- Improve readability without sacrificing functionality
- Add appropriate comments explaining the optimization techniques

### 3. Architectural Refactoring

The `monolithic_app.js` represents a small monolithic application.

**Challenge:** Use GitHub Copilot to:
- Refactor into a microservices or modular architecture
- Apply appropriate design patterns
- Implement proper separation of concerns
- Create interfaces between modules

## Using GitHub Copilot for Advanced Refactoring

1. Start by asking Copilot to analyze the existing code and identify issues
2. Ask for recommendations on modern architecture patterns that would fit
3. Break down the refactoring into manageable steps
4. Use inline chat to ask about specific sections of code
5. Have Copilot generate tests to verify the refactored code behaves correctly

## Best Practices for Refactoring with Copilot

- Always understand what the original code does before refactoring
- Break large refactoring tasks into smaller steps
- Verify each change with tests before moving to the next step
- Use Copilot to help identify edge cases you might have missed
- Ask Copilot to explain its refactoring decisions to better understand modern practices
115 changes: 115 additions & 0 deletions github-copilot-features/advanced-refactor/complex_algorithm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
# An inefficient implementation of a data processing algorithm
# This code contains performance bottlenecks and inefficient data structures
# that can be optimized with GitHub Copilot's assistance

def process_large_dataset(data, threshold=0.5):
"""
Process a large dataset with an inefficient algorithm.
This function has several performance issues:
- Redundant calculations
- Inefficient data structures
- Unnecessary copying of data
- Poor algorithm choice

Parameters:
- data: List of dictionaries with 'id', 'value', and 'metadata' fields
- threshold: Threshold value for filtering

Returns:
- Processed and filtered data
"""
# Initialize results
results = []

# Pre-process: extract values for later use
all_values = []
for item in data:
all_values.append(item['value'])

# Calculate statistics - inefficiently
total = 0
for val in all_values:
total += val
mean = total / len(all_values) if len(all_values) > 0 else 0

# Calculate variance - inefficiently
variance = 0
for val in all_values:
variance += (val - mean) ** 2
variance = variance / len(all_values) if len(all_values) > 0 else 0

# Process each item - with redundant calculations
for item in data:
# Normalize value - redundantly calculated for each item
normalized_value = (item['value'] - mean) / (variance ** 0.5) if variance > 0 else 0

# Filter based on threshold
if normalized_value > threshold:
# Deep copy the item to avoid modifying original data
processed_item = {}
for key in item:
processed_item[key] = item[key]

# Add derived fields
processed_item['normalized_value'] = normalized_value
processed_item['is_significant'] = normalized_value > 2 * threshold

# Add to results
results.append(processed_item)

# Sort results - inefficiently
for i in range(len(results)):
for j in range(i + 1, len(results)):
if results[i]['normalized_value'] < results[j]['normalized_value']:
results[i], results[j] = results[j], results[i]

# Calculate additional metrics for filtered items - redundant loops
metadata_counts = {}
for item in results:
meta = item['metadata']
if meta in metadata_counts:
metadata_counts[meta] = metadata_counts[meta] + 1
else:
metadata_counts[meta] = 1

# Add frequency information to results - another loop through results
for item in results:
item['frequency'] = metadata_counts[item['metadata']] / len(results) if len(results) > 0 else 0

return results


def generate_test_data(size=1000):
"""
Generate test data for demonstration.
"""
import random
data = []
for i in range(size):
data.append({
'id': i,
'value': random.random() * 100,
'metadata': random.choice(['A', 'B', 'C', 'D', 'E'])
})
return data


# Example usage
if __name__ == "__main__":
# Generate sample data
test_data = generate_test_data(size=5000)

# Time the processing
import time
start_time = time.time()

# Process data
result = process_large_dataset(test_data)

# Print execution time
print(f"Processed {len(test_data)} items in {time.time() - start_time:.4f} seconds")
print(f"Result contains {len(result)} items")

# Print first few results
for i, item in enumerate(result[:5]):
print(f"{i+1}. ID: {item['id']}, Value: {item['value']:.2f}, Normalized: {item['normalized_value']:.2f}")
183 changes: 183 additions & 0 deletions github-copilot-features/advanced-refactor/legacy_service.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
// This is an example of legacy service code that could benefit from advanced refactoring
// It contains multiple code smells and anti-patterns that GitHub Copilot can help identify and fix

// Global variables and state
var users = [];
var orders = [];
var currentStatus = 'idle';

// Helper functions
function checkUserPermission(userId, action) {
var user = null;
for (var i = 0; i < users.length; i++) {
if (users[i].id === userId) {
user = users[i];
break;
}
}

if (user === null) {
return false;
}

if (action === 'view') {
return user.role === 'admin' || user.role === 'viewer' || user.role === 'editor';
} else if (action === 'edit') {
return user.role === 'admin' || user.role === 'editor';
} else if (action === 'delete') {
return user.role === 'admin';
} else {
return false;
}
}

// Main service functions
function addUser(id, name, email, role) {
if (!id || !name || !email) {
console.error('Missing required fields');
return false;
}

for (var i = 0; i < users.length; i++) {
if (users[i].id === id) {
console.error('User already exists');
return false;
}
}

currentStatus = 'adding';

// Simulate API call delay
setTimeout(function() {
users.push({
id: id,
name: name,
email: email,
role: role || 'viewer',
createdAt: new Date().toISOString()
});

currentStatus = 'idle';
console.log('User added successfully');
}, 100);

return true;
}

function getUser(id) {
for (var i = 0; i < users.length; i++) {
if (users[i].id === id) {
return users[i];
}
}
return null;
}

function deleteUser(userId, requestingUserId) {
if (!checkUserPermission(requestingUserId, 'delete')) {
console.error('Permission denied');
return false;
}

var userIndex = -1;
for (var i = 0; i < users.length; i++) {
if (users[i].id === userId) {
userIndex = i;
break;
}
}

if (userIndex === -1) {
console.error('User not found');
return false;
}

// Check if user has orders
var hasOrders = false;
for (var i = 0; i < orders.length; i++) {
if (orders[i].userId === userId) {
hasOrders = true;
break;
}
}

if (hasOrders) {
console.error('Cannot delete user with orders');
return false;
}

currentStatus = 'deleting';

// Simulate API call delay
setTimeout(function() {
users.splice(userIndex, 1);
currentStatus = 'idle';
console.log('User deleted successfully');
}, 100);

return true;
}

function createOrder(userId, items, quantity) {
var user = getUser(userId);
if (!user) {
console.error('User not found');
return false;
}

if (!items || !quantity) {
console.error('Missing order details');
return false;
}

currentStatus = 'ordering';

// Simulate API call delay
setTimeout(function() {
var order = {
id: 'order_' + Date.now(),
userId: userId,
items: items,
quantity: quantity,
status: 'created',
createdAt: new Date().toISOString()
};

orders.push(order);
currentStatus = 'idle';
console.log('Order created successfully');
}, 100);

return true;
}

function getOrdersByUser(userId, requestingUserId) {
if (!checkUserPermission(requestingUserId, 'view')) {
console.error('Permission denied');
return null;
}

var userOrders = [];
for (var i = 0; i < orders.length; i++) {
if (orders[i].userId === userId) {
userOrders.push(orders[i]);
}
}

return userOrders;
}

// Service status
function getStatus() {
return currentStatus;
}

// Module exports (CommonJS style)
module.exports = {
addUser: addUser,
getUser: getUser,
deleteUser: deleteUser,
createOrder: createOrder,
getOrdersByUser: getOrdersByUser,
getStatus: getStatus
};
Loading