Skip to content

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:

python
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 False

After (MyDeskBot refactoring):

python
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:

javascript
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):

javascript
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:

java
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):

java
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:

javascript
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):

javascript
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:

python
def fetch_user_data(user_id):
    response = requests.get(f'/api/users/{user_id}')
    data = response.json()
    return data

After (MyDeskBot refactoring):

python
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:

javascript
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²)):

javascript
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:

python
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 product

After (MyDeskBot refactoring):

python
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

  1. Select the code to refactor
  2. Right-click
  3. Choose "Refactor with MyDeskBot"
  4. Select the type of refactoring
  5. Review and apply changes

Method 2: Keyboard Shortcut

  1. Select code
  2. Press Ctrl+Shift+R (Windows/Linux) or Cmd+Shift+R (macOS)
  3. MyDeskBot shows refactoring options
  4. Choose the desired refactoring

Method 3: Inline Chat

  1. Select code
  2. Press Ctrl+Shift+M for inline chat
  3. Describe what you want:
    Refactor this to use the Strategy pattern
  4. 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 callbacks
Refactor to follow SOLID principles
Refactor to be more testable

Configuration

Refactoring Behavior

json
{
  "mydeskbot.refactoring": {
    "autoApply": false,
    "showDiff": true,
    "preserveFormatting": true,
    "addComments": false
  }
}

Safety Options

json
{
  "mydeskbot.refactoring.safety": {
    "requireConfirmation": true,
    "backupBeforeChanges": true,
    "limitScope": "selection"
  }
}

Best Practices

1. Small Steps

Refactor in small, incremental changes:

python
# 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 pass

3. Review Changes

Always review AI suggestions:

javascript
// 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:

python
# 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 duplicates

Common 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

javascript
// 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

python
# 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

See Also