ARTICLE AD BOX
The Problem: I am building a simple data processing tool. Depending on the file format (JSON, XML, or CSV), I need to apply different parsing logic. Currently, I’m using a long chain of if-elif statements inside one class. As I add more formats, this class becomes hard to maintain and violates the Single Responsibility Principle.
Research done: I’ve read about the Strategy Pattern and Interface-based design. I understand that I should encapsulate each algorithm into a separate class, but as a beginner, I’m struggling with how to dynamically select the right strategy in Python without creating another "if-elif" mess in the factory.
class DataProcessor: def process(self, format_type, data): if format_type == "json": return f"Parsing JSON: {data}" elif format_type == "xml": return f"Parsing XML: {data}" elif format_type == "csv": return f"Parsing CSV: {data}" else: raise ValueError("Unsupported format") # Usage processor = DataProcessor() print(processor.process("json", "{'key': 'value'}"))What I want to achieve: I want to transform this into a clean architecture where:
Each parser is a separate class/strategy.
The DataProcessor doesn't need to be modified when a new format is added.
What I've tried: I tried creating a dictionary of classes, but I'm not sure if this is the "Pythonic" way to implement the Strategy pattern or if there is a more standard approach using ABC (Abstract Base Classes).
How can I properly implement this to keep my code scalable?
