Code Refactoring
Let MyDeskBot help you improve code quality, readability, and maintainability with AI-powered refactoring suggestions.
Overview
MyDeskBot's refactoring capabilities analyze your code and suggest improvements that follow best practices, design patterns, and industry standards.
Refactoring Types
1. Simplify Code
Make complex logic simpler and more readable:
Before:
def check_permission(user, action):
if user is not None:
if user.role is not None:
if user.role.permissions is not None:
if action in user.role.permissions:
return True
return FalseAfter (MyDeskBot refactoring):
def check_permission(user, action):
if not user or not user.role:
return False
return action in (user.role.permissions or [])2. Extract Function/Method
Break down large functions into smaller, reusable ones:
Before:
function processOrder(order) {
// Validate
if (!order.customerId || !order.items.length) {
throw new Error("Invalid order");
}
// Calculate totals
let subtotal = 0;
order.items.forEach((item) => {
subtotal += item.price * item.quantity;
});
const tax = subtotal * 0.1;
const total = subtotal + tax;
// Save to database
const dbOrder = {
id: generateId(),
customerId: order.customerId,
items: order.items,
subtotal,
tax,
total,
};
database.save(dbOrder);
return dbOrder;
}After (MyDeskBot refactoring):
function processOrder(order) {
validateOrder(order);
const totals = calculateOrderTotals(order);
return saveOrder(order, totals);
}
function validateOrder(order) {
if (!order.customerId || !order.items.length) {
throw new Error("Invalid order");
}
}
function calculateOrderTotals(order) {
const subtotal = order.items.reduce(
(sum, item) => sum + item.price * item.quantity,
0,
);
return {
subtotal,
tax: subtotal * 0.1,
total: subtotal * (1 + 0.1),
};
}
function saveOrder(order, totals) {
const dbOrder = {
id: generateId(),
customerId: order.customerId,
items: order.items,
...totals,
};
return database.save(dbOrder);
}3. Improve Naming
Use more descriptive and consistent names:
Before:
public class Data {
private List<String> d;
private int c;
public void add(String s) {
d.add(s);
c++;
}
public int getC() {
return c;
}
}After (MyDeskBot refactoring):
public class StringCollection {
private final List<String> elements;
private int size;
public StringCollection() {
this.elements = new ArrayList<>();
this.size = 0;
}
public void add(String element) {
elements.add(element);
size++;
}
public int size() {
return size;
}
}4. Apply Design Patterns
Implement design patterns:
Before:
class LoggerFactory {
createLogger(type) {
if (type === "console") {
return new ConsoleLogger();
} else if (type === "file") {
return new FileLogger();
} else if (type === "remote") {
return new RemoteLogger();
}
throw new Error("Unknown logger type");
}
}After (MyDeskBot refactoring - Factory Pattern):
class LoggerFactory {
private static creators = {
console: () => new ConsoleLogger(),
file: () => new FileLogger(),
remote: () => new RemoteLogger(),
};
createLogger(type) {
const creator = this.creators[type];
if (!creator) {
throw new Error(`Unknown logger type: ${type}`);
}
return creator();
}
}5. Error Handling
Improve error handling and resilience:
Before:
def fetch_user_data(user_id):
response = requests.get(f'/api/users/{user_id}')
data = response.json()
return dataAfter (MyDeskBot refactoring):
def fetch_user_data(user_id: int) -> dict:
"""Fetch user data from API with proper error handling."""
try:
response = requests.get(
f'/api/users/{user_id}',
timeout=10
)
response.raise_for_status()
return response.json()
except requests.HTTPError as e:
logger.error(f"HTTP error: {e}")
raise UserFetchError(f"Failed to fetch user {user_id}")
except requests.Timeout:
logger.error("Request timeout")
raise UserFetchError("Request timed out")
except requests.RequestException as e:
logger.error(f"Request error: {e}")
raise UserFetchError("Failed to connect to API")6. Performance Optimization
Optimize for better performance:
Before:
function filterUniqueUsers(users) {
return users.filter((user) => {
return !users.find((u) => u.id === user.id && u !== user);
});
}After (MyDeskBot refactoring - O(n) instead of O(n²)):
function filterUniqueUsers(users) {
const seen = new Set();
return users.filter((user) => {
if (seen.has(user.id)) {
return false;
}
seen.add(user.id);
return true;
});
}7. Reduce Code Duplication
Eliminate repeated code:
Before:
def create_user(name, email):
if not name or not email:
raise ValueError("Invalid input")
user = User(name=name, email=email)
user.created_at = datetime.now()
user.updated_at = datetime.now()
return user
def create_product(name, price):
if not name or price is None:
raise ValueError("Invalid input")
product = Product(name=name, price=price)
product.created_at = datetime.now()
product.updated_at = datetime.now()
return productAfter (MyDeskBot refactoring):
def create_timestamped_entity(cls, **kwargs):
"""Create entity with automatic timestamps."""
if not all(kwargs.values()):
raise ValueError("Invalid input")
now = datetime.now()
return cls(**kwargs, created_at=now, updated_at=now)
def create_user(name, email):
return create_timestamped_entity(User, name=name, email=email)
def create_product(name, price):
return create_timestamped_entity(Product, name=name, price=price)How to Refactor
Method 1: Right-Click Refactor
- Select the code to refactor
- Right-click
- Choose "Refactor with MyDeskBot"
- Select the type of refactoring
- Review and apply changes
Method 2: Keyboard Shortcut
- Select code
- Press
Ctrl+Shift+R(Windows/Linux) orCmd+Shift+R(macOS) - MyDeskBot shows refactoring options
- Choose the desired refactoring
Method 3: Inline Chat
- Select code
- Press
Ctrl+Shift+Mfor inline chat - Describe what you want:
Refactor this to use the Strategy pattern - MyDeskBot provides the refactored code
Refactoring Options
Available Options
- Simplify: Make code simpler and clearer
- Extract: Extract functions/methods/classes
- Rename: Improve naming conventions
- Optimize: Improve performance
- Apply Pattern: Apply design patterns
- Add Error Handling: Improve error handling
- Reduce Duplication: Eliminate repeated code
- Improve Type Safety: Add or improve types
- Modernize: Use modern language features
- Custom: Describe your own refactoring goal
Custom Refactoring
Ask MyDeskBot for specific refactoring:
Refactor this to use async/await instead of callbacksRefactor to follow SOLID principlesRefactor to be more testableConfiguration
Refactoring Behavior
{
"mydeskbot.refactoring": {
"autoApply": false,
"showDiff": true,
"preserveFormatting": true,
"addComments": false
}
}Safety Options
{
"mydeskbot.refactoring.safety": {
"requireConfirmation": true,
"backupBeforeChanges": true,
"limitScope": "selection"
}
}Best Practices
1. Small Steps
Refactor in small, incremental changes:
# Don't do everything at once
# Step 1: Extract function
def calculate_discount(price, discount_rate):
return price * (1 - discount_rate)
# Step 2: Add type hints
def calculate_discount(price: float, discount_rate: float) -> float:
return price * (1 - discount_rate)
# Step 3: Add validation
def calculate_discount(price: float, discount_rate: float) -> float:
if price < 0 or discount_rate < 0 or discount_rate > 1:
raise ValueError("Invalid input")
return price * (1 - discount_rate)2. Keep Tests Passing
Run tests after each refactoring:
1. Write tests (if not already)
2. Run tests to ensure they pass
3. Refactor
4. Run tests again
5. Commit if tests pass3. Review Changes
Always review AI suggestions:
// MyDeskBot might suggest:
const result = data.map((x) => x * 2).filter((x) => x > 10);
// But you might prefer:
const result = data
.filter((x) => x * 2 > 10) // Filter first for performance
.map((x) => x * 2);4. Add Documentation
Document why you refactored:
# Refactored to reduce complexity from O(n²) to O(n)
# Using set for O(1) lookups instead of nested loops
def find_duplicates(items):
seen = set()
duplicates = set()
for item in items:
if item in seen:
duplicates.add(item)
seen.add(item)
return duplicatesCommon Refactoring Scenarios
Scenario 1: Long Method
Problem: Method is too long and does too much
Solution: Extract smaller methods
Scenario 2: Duplicate Code
Problem: Same code appears in multiple places
Solution: Extract to a shared function
Scenario 3: Magic Numbers
Problem: Numbers without context
Solution: Extract to named constants
// Before
const total = price * 0.08; // What is 0.08?
// After
const TAX_RATE = 0.08;
const total = price * TAX_RATE;Scenario 4: Deep Nesting
Problem: Too many nested conditionals
Solution: Use guard clauses or early returns
# Before
def process_order(order):
if order:
if order.items:
if order.items.length > 0:
# process
pass
# After
def process_order(order):
if not order or not order.items or not len(order.items) > 0:
return
# process