7 Rules to Write Highly Scalable Code with Practical Examples 🚀
Tags: beginners, programming, tutorial, productivity
Published: 2023-07-28 03:26:26

Hey fellow developers!

Today, let's dive into the art of writing scalable code. Writing scalable code ensures that your software can handle growing demands and maintain its performance. 

Here are some strategies, with examples in the analogy of Noob Way vs Pro Way, to help you level up your coding game! 👩‍💻

---

## Rule 1: Optimise Data Structures

🟢 Noob Way: Using a basic list for a large dataset.

```python
# Noob Way
data = [1, 2, 3, ... 1000000]
for item in data:
    # do something
```

🟣 Pro Way: Choosing the right data structure for the job.

```python
# Pro Way
data = set([1, 2, 3, ... 1000000])
for item in data:
    # do something
```

---

## Rule 2: Efficient Algorithm Selection

🟢 Noob Way: Using a naive algorithm with high time complexity.

```python
# Noob Way
def sum_numbers(n):
    sum = 0
    for i in range(n):
        sum += i
    return sum
```

🟣 Pro Way: Utilising an optimised algorithm with lower time complexity.

```python
# Pro Way
def sum_numbers(n):
    return (n * (n + 1)) // 2
```

---

## Rule 3: Modularisation and Code Reusability

🟢 Noob Way: Writing long monolithic functions.

```python
# Noob Way
def complex_task(data):
    # lots of code here
    return result
```

🟣 Pro Way: Breaking down tasks into smaller, reusable functions.

```python
# Pro Way
def sub_task1(data):
    # do something
    return result

def sub_task2(data):
    # do something else
    return result

def complex_task(data):
    result1 = sub_task1(data)
    result2 = sub_task2(data)
    # combine results and do more processing
    return final_result
```

---

## Rule 4: Caching and Memoisation

🟢 Noob Way: Recalculating expensive operations repeatedly.

```python
# Noob Way
def fibonacci(n):
    if n <= 1:
        return n
    else:
        return fibonacci(n-1) + fibonacci(n-2)
```

🟣 Pro Way: Implementing caching to store previous results.

```python
# Pro Way
from functools import lru_cache

@lru_cache(maxsize=None)
def fibonacci(n):
    if n <= 1:
        return n
    else:
        return fibonacci(n-1) + fibonacci(n-2)
```

---

## Rule 5: Avoiding Global Variables

🟢 Noob Way: Reliance on global variables throughout the code.

```python
# Noob Way
global_var = 10

def add_to_global(num):
    global global_var
    global_var += num

def print_global():
    print(global_var)
```

🟣 Pro Way: Embracing encapsulation and passing variables explicitly.

```python
# Pro Way
class Counter:
    def __init__(self):
        self.value = 10

    def add_to_counter(self, num):
        self.value += num

    def get_counter_value(self):
        return self.value

counter = Counter()
counter.add_to_counter(5)
print(counter.get_counter_value())
```

---

## Rule 6: Asynchronous Programming

🟢 Noob Way: Using synchronous operations, causing delays.

```python
# Noob Way
import requests

def fetch_data(url):
    response = requests.get(url)
    return response.text

data = fetch_data('https://example.com/data')
```

🟣 Pro Way: Leveraging asynchronous operations for improved performance.

```python
# Pro Way
import aiohttp
import asyncio

async def fetch_data(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as response:
            return await response.text()

async def main():
    data = await fetch_data('https://example.com/data')
    # process data here

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
```

---

## Rule 7: Handling Errors Gracefully



🟢 Noob Way: Ignoring errors and hoping for the best.

```python
# Noob Way
def divide(a, b):
    try:
        result = a / b
    except:
        result = None
    return result
```

🟣 Pro Way: Implementing proper error handling and logging.

```python
# Pro Way
import logging

def divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError as e:
        logging.error("Attempted to divide by zero.")
        result = None
    except Exception as e:
        logging.error(f"An error occurred: {e}")
        result = None
    return result
```

---

## Before we go...

Thanks for reading!

If you loved this, drop a like and consider following me :)

I share insights on flutter, open-source & software development to help you become a 10x developer.

Got any doubt or wanna chat? React out to me on [twitter](https://twitter.com/iamyatendrak) or [linkedin](https://www.linkedin.com/in/yatendra2001/).