How to Avoid Nesting If Statement: Best Practices

1. Early Returns

def process_user_input(input):  
    if input:  
        if isinstance(input, str):  
            if len(input) > 5:  
                # Process the input  
                print("Processing input")  
            else:  
                print("Input is too short")  
        else:  
            print("Input is not a string")  
    else:  
        print("Input is empty")
def process_user_input(input):  
    if not input:  
        print("Input is empty")  
        return  
      
    if not isinstance(input, str):  
        print("Input is not a string")  
        return  
      
    if len(input) <= 5:  
        print("Input is too short")  
        return  
      
    # Process the input  
    print("Processing input")
def process_order(order):  
    if order:  
        if order.is_valid:  
            if len(order.items) > 0:  
                # Process the order  
                print("Order processed")  
            else:  
                print("Order has no items")  
        else:  
            print("Order is not valid")  
    else:  
        print("No order provided")  
def process_order(order):  
    if not order:  
        print("No order provided")  
        return  
      
    if not order.is_valid:  
        print("Order is not valid")  
        return  
      
    if len(order.items) == 0:  
        print("Order has no items")  
        return  
      
    # Process the order  
    print("Order processed")
def handle_user_role(role):  
    if role == "admin":  
        # Handle admin  
        print("Admin access")  
    elif role == "editor":  
        # Handle editor  
        print("Editor access")  
    elif role == "viewer":  
        # Handle viewer  
        print("Viewer access")  
    else:  
        print("Unknown role")  
def handle_admin():  
    print("Admin access")  
  
def handle_editor():  
    print("Editor access")  
  
def handle_viewer():  
    print("Viewer access")  
  
def handle_unknown():  
    print("Unknown role")  
  
role_actions = {  
    "admin": handle_admin,  
    "editor": handle_editor,  
    "viewer": handle_viewer  
}  
  
def handle_user_role(role):  
    role_actions.get(role, handle_unknown)()
class PaymentProcessor:  
    def process(self, payment_type):  
        if payment_type == "credit_card":  
            self.process_credit_card()  
        elif payment_type == "paypal":  
            self.process_paypal()  
        elif payment_type == "bitcoin":  
            self.process_bitcoin()  
        else:  
            raise ValueError("Unknown payment type")  
  
    def process_credit_card(self):  
        print("Processing credit card payment")  
  
    def process_paypal(self):  
        print("Processing PayPal payment")  
  
    def process_bitcoin(self):  
        print("Processing Bitcoin payment")  
class Payment:  
    def process(self):  
        pass  
  
class CreditCardPayment(Payment):  
    def process(self):  
        print("Processing credit card payment")  
  
class PayPalPayment(Payment):  
    def process(self):  
        print("Processing PayPal payment")  
  
class BitcoinPayment(Payment):  
    def process(self):  
        print("Processing Bitcoin payment")  
  
class PaymentProcessor:  
    def process(self, payment: Payment):  
        payment.process()  
  
# Usage  
payment_processor = PaymentProcessor()  
payment_processor.process(CreditCardPayment())  
payment_processor.process(PayPalPayment())  
payment_processor.process(BitcoinPayment())  
class Order:  
    def __init__(self, total_amount, discount_type):  
        self.total_amount = total_amount  
        self.discount_type = discount_type  
  
    def calculate_discount(self):  
        if self.discount_type == "seasonal":  
            return self.total_amount * 0.1  
        elif self.discount_type == "clearance":  
            return self.total_amount * 0.5  
        elif self.discount_type == "loyalty":  
            return self.total_amount * 0.2  
        else:  
            return 0
class DiscountStrategy:  
    def calculate_discount(self, total_amount):  
        pass  
  
class SeasonalDiscount(DiscountStrategy):  
    def calculate_discount(self, total_amount):  
        return total_amount * 0.1  
  
class ClearanceDiscount(DiscountStrategy):  
    def calculate_discount(self, total_amount):  
        return total_amount * 0.5  
  
class LoyaltyDiscount(DiscountStrategy):  
    def calculate_discount(self, total_amount):  
        return total_amount * 0.2  
  
class Order:  
    def __init__(self, total_amount, discount_strategy: DiscountStrategy):  
        self.total_amount = total_amount  
        self.discount_strategy = discount_strategy  
  
    def calculate_discount(self):  
        return self.discount_strategy.calculate_discount(self.total_amount)  
  
# Usage  
order = Order(100, SeasonalDiscount())  
discount = order.calculate_discount()  
print(f"Discount: {discount}")  
def check_conditions(a, b, c):  
    if a:  
        if b:  
            if c:  
                print("All conditions are true")  
def check_conditions(a, b, c):  
    if a and b and c:  
        print("All conditions are true")  
def get_discount(is_member):  
    if is_member:  
        discount = 10  
    else:  
        discount = 0  
    return discount  
def get_discount(is_member):  
    return 10 if is_member else 0  

Leave a Reply

Your email address will not be published. Required fields are marked *

×