Skip to main content

Command Palette

Search for a command to run...

7 Rules to Write Highly Scalable Code with Practical Examples πŸš€

Published
β€’3 min read
7 Rules to Write Highly Scalable Code with Practical Examples πŸš€
Y

HeyπŸ‘‹, I am a Flutter App Developer with a keen interest in fixing real-world problems with my skills.

I love to read books. I have read multiple books on start-ups and productivity. Some of my favourite reads are Zero to One, Steve Jobs, The Almanack of Ravikant and Hooked.

Nothing excites me more than exchanging opinions through productive conversations.

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.

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

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

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

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

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

Rule 3: Modularisation and Code Reusability

🟒 Noob Way: Writing long monolithic functions.

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

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

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

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

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

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

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

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

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

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

🟣 Pro Way: Implementing proper error handling and logging.

# 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 doubts or wanna chat? React to me on Twitter or LinkedIn.

D

Good insights. Thanks for writing.

2
Y

Thanks Devkant :)

More from this blog

Yatendra Kumar

44 posts

HeyπŸ‘‹, I am a Flutter App Developer with a keen interest in fixing real-world problems with my skills. Currently, I am building a startup in stealth mode that was incubated by google developers.