Coding Hacks That Will 10x Your Productivity

After years of coding, you pick up tricks that make you significantly more productive. Here are the coding hacks that will transform how you write code.

Terminal and Command Line Hacks

Powerful Git Aliases

# Add these to your ~/.gitconfig
[alias]
    co = checkout
    br = branch
    ci = commit
    st = status
    unstage = reset HEAD --
    last = log -1 HEAD
    visual = !gitk
    
    # Advanced aliases
    lg = log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
    undo = reset --soft HEAD^
    amend = commit --amend --no-edit
    pushf = push --force-with-lease
    
    # Find commits that added or removed a string
    grep-history = log -p -S

Bash/Zsh Productivity Functions

# Quick directory navigation
alias ..='cd ..'
alias ...='cd ../..'
alias ....='cd ../../..'

# Better ls
alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'

# Quick file operations
mkcd() { mkdir -p "$1" && cd "$1"; }
extract() {
    if [ -f $1 ] ; then
        case $1 in
            *.tar.bz2)   tar xjf $1     ;;
            *.tar.gz)    tar xzf $1     ;;
            *.bz2)       bunzip2 $1     ;;
            *.rar)       unrar e $1     ;;
            *.gz)        gunzip $1      ;;
            *.tar)       tar xf $1      ;;
            *.tbz2)      tar xjf $1     ;;
            *.tgz)       tar xzf $1     ;;
            *.zip)       unzip $1       ;;
            *.Z)         uncompress $1  ;;
            *.7z)        7z x $1        ;;
            *)     echo "'$1' cannot be extracted via extract()" ;;
        esac
    else
        echo "'$1' is not a valid file"
    fi
}

Code Editor Superpowers

VS Code Snippets

// Add to your snippets file
{
    "Console Log": {
        "prefix": "cl",
        "body": [
            "console.log('$1:', $1);"
        ],
        "description": "Console log with label"
    },
    "Try Catch Block": {
        "prefix": "tryc",
        "body": [
            "try {",
            "    $1",
            "} catch (error) {",
            "    console.error('Error:', error);",
            "    $2",
            "}"
        ],
        "description": "Try catch block"
    },
    "Async Function": {
        "prefix": "afn",
        "body": [
            "const $1 = async ($2) => {",
            "    try {",
            "        $3",
            "    } catch (error) {",
            "        console.error('Error in $1:', error);",
            "        throw error;",
            "    }",
            "};"
        ],
        "description": "Async function with error handling"
    }
}

Multi-Cursor Magic

// Select all occurrences: Ctrl+Shift+L (Cmd+Shift+L on Mac)
// Add cursor above/below: Ctrl+Alt+Up/Down
// Column selection: Shift+Alt+Drag

// Example: Quickly transform array
const users = [
    'john@example.com',
    'jane@example.com', 
    'bob@example.com'
];

// Use multi-cursor to transform to:
const users = [
    { email: 'john@example.com', active: true },
    { email: 'jane@example.com', active: true },
    { email: 'bob@example.com', active: true }
];

JavaScript/TypeScript Hacks

Destructuring Tricks

// Rename while destructuring
const { name: userName, age: userAge } = user;

// Default values with destructuring
const { theme = 'dark', language = 'en' } = settings;

// Swap variables
let a = 1, b = 2;
[a, b] = [b, a];

// Extract specific array elements
const [first, , third] = array; // Skip second element

// Rest in object destructuring
const { id, ...userWithoutId } = user;

// Nested destructuring
const { address: { street, city } } = user;

Array Method Chaining

// Transform data in one chain
const processedUsers = users
    .filter(user => user.active)
    .map(user => ({
        ...user,
        fullName: `${user.firstName} ${user.lastName}`,
        age: calculateAge(user.birthDate)
    }))
    .sort((a, b) => a.age - b.age)
    .slice(0, 10);

// Group by with reduce
const groupBy = (array, key) => 
    array.reduce((groups, item) => {
        const group = item[key];
        groups[group] = groups[group] || [];
        groups[group].push(item);
        return groups;
    }, {});

const usersByRole = groupBy(users, 'role');

Async/Await Patterns

// Parallel execution with error handling
const fetchUserData = async (userId) => {
    const [user, posts, comments] = await Promise.allSettled([
        fetchUser(userId),
        fetchUserPosts(userId),
        fetchUserComments(userId)
    ]);
    
    return {
        user: user.status === 'fulfilled' ? user.value : null,
        posts: posts.status === 'fulfilled' ? posts.value : [],
        comments: comments.status === 'fulfilled' ? comments.value : []
    };
};

// Retry with exponential backoff
const retryWithBackoff = async (fn, maxRetries = 3) => {
    for (let i = 0; i < maxRetries; i++) {
        try {
            return await fn();
        } catch (error) {
            if (i === maxRetries - 1) throw error;
            await new Promise(resolve => 
                setTimeout(resolve, Math.pow(2, i) * 1000)
            );
        }
    }
};

Python Productivity Hacks

List Comprehensions and Generators

# List comprehension with condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]

# Dictionary comprehension
word_lengths = {word: len(word) for word in words}

# Generator for memory efficiency
def fibonacci():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

# Use itertools for powerful combinations
from itertools import groupby, chain, combinations

# Group consecutive elements
data = [1, 1, 2, 2, 2, 3, 1, 1]
grouped = [(k, len(list(g))) for k, g in groupby(data)]
# [(1, 2), (2, 3), (3, 1), (1, 2)]

Context Managers

# Custom context manager
from contextlib import contextmanager
import time

@contextmanager
def timer(name):
    start = time.time()
    try:
        yield
    finally:
        print(f"{name} took {time.time() - start:.2f} seconds")

# Usage
with timer("Database query"):
    result = expensive_database_query()

# File operations with automatic cleanup
with open('file.txt', 'r') as f:
    content = f.read()
    # File automatically closed

Debugging Superpowers

Advanced Console Techniques

// Console table for objects
console.table(users);

// Console group for organized logging
console.group('User Processing');
console.log('Processing user:', user.name);
console.log('User role:', user.role);
console.groupEnd();

// Console time for performance
console.time('API Call');
await fetchData();
console.timeEnd('API Call');

// Conditional logging
console.assert(user.age > 0, 'User age should be positive');

// Stack trace
console.trace('Execution path');

Python Debugging

# IPython debugger
import ipdb; ipdb.set_trace()

# Pretty printing
from pprint import pprint
pprint(complex_data_structure)

# Inspect object attributes
import inspect
print(inspect.getmembers(obj))

# Profile code performance
import cProfile
cProfile.run('expensive_function()')

Database Query Optimization

SQL Tricks

-- Use EXPLAIN to understand query execution
EXPLAIN ANALYZE SELECT * FROM users WHERE email = 'user@example.com';

-- Window functions for analytics
SELECT 
    name,
    salary,
    AVG(salary) OVER (PARTITION BY department) as dept_avg,
    ROW_NUMBER() OVER (ORDER BY salary DESC) as salary_rank
FROM employees;

-- Efficient pagination
SELECT * FROM posts 
WHERE id > :last_id 
ORDER BY id 
LIMIT 20;

-- Bulk operations
INSERT INTO users (name, email) 
VALUES 
    ('John', 'john@example.com'),
    ('Jane', 'jane@example.com')
ON DUPLICATE KEY UPDATE 
    name = VALUES(name);

Automation Scripts

Package.json Scripts

{
  "scripts": {
    "dev": "concurrently \"npm run server\" \"npm run client\"",
    "test:watch": "jest --watch --coverage",
    "lint:fix": "eslint . --fix && prettier --write .",
    "pre-commit": "lint-staged",
    "deploy": "npm run build && npm run test && git push origin main",
    "clean": "rm -rf node_modules dist && npm install",
    "analyze": "npm run build && npx webpack-bundle-analyzer dist/stats.json"
  }
}

Git Hooks for Quality

#!/bin/sh
# .git/hooks/pre-commit
npm run lint:fix
npm run test
git add -A

These hacks aren’t just about writing code faster—they’re about writing better code with less effort. The key is to gradually incorporate these into your workflow until they become second nature.