Principios de Diseño de Software: Ejemplo Práctico en Python

Guía de SOLID: SRP, OCP, LSP, ISP y DIP con un ejemplo en Python para un sistema de notificaciones extensible, mantenible y testeable.

15 sept 2025 • 3 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Introducción: Los principios de diseño de software son guías fundamentales que permiten a los desarrolladores crear soluciones mantenibles, escalables y flexibles. Más allá de escribir código que funcione, un buen diseño facilita la ampliación, comprensión y prueba del software a lo largo del tiempo. Entre principios clave están SOLID, DRY, KISS y YAGNI. Este artículo se centra en SOLID y muestra su aplicación con un ejemplo práctico en Python orientado a un sistema de notificaciones extensible y testeable.

Resumen de los principios SOLID: SRP Principio de Responsabilidad Única un componente debe tener una sola razón para cambiar. OCP Principio Abierto/Cerrado las entidades deben estar abiertas a extensión y cerradas a modificación. LSP Principio de Sustitución de Liskov los subtipos deben ser sustituibles por sus tipos base. ISP Principio de Segregación de Interfaces los clientes no deben depender de interfaces que no usan. DIP Principio de Inversión de Dependencias módulos de alto nivel no deben depender de módulos de bajo nivel sino de abstracciones.

Ejemplo práctico: sistema de notificaciones en Python. Imaginemos una aplicación que envía notificaciones por varios canales Email y SMS. El objetivo es poder añadir canales adicionales como Push o Webhooks sin modificar código existente, favoreciendo la extensibilidad.

Definir una abstracción para notificaciones

from abc import ABC, abstractmethod

class Notifier(ABC):

@abstractmethod

def send(self, message: str, recipient: str):

pass

Implementaciones concretas

class EmailNotifier(Notifier):

def send(self, message: str, recipient: str):

print(message, recipient)

class SMSNotifier(Notifier):

def send(self, message: str, recipient: str):

print(message, recipient)

Servicio de notificación usando inyección de dependencias

class NotificationService:

def __init__(self, notifier: Notifier):

self.notifier = notifier

def notify(self, message: str, recipient: str):

self.notifier.send(message, recipient)

Ejemplo de uso

email_notifier = EmailNotifier()

sms_notifier = SMSNotifier()

service = NotificationService(email_notifier)

service.notify(message_welcome, user_email)

service = NotificationService(sms_notifier)

service.notify(message_code, phone_number)

Explicación y vínculo con SOLID: Cada clase concreta tiene una única responsabilidad cumpliendo SRP. Al definir la abstracción Notifier y construir nuevas implementaciones se respeta OCP ya que se extiende sin modificar código existente. NotificationService depende de la abstracción Notifier aplicando DIP y permite sustituir implementaciones concretas sin cambios en el servicio, lo que satisface LSP. ISP invita a diseñar interfaces específicas cuando convenga para no forzar dependencias innecesarias.

Sobre Q2BSTUDIO: En Q2BSTUDIO somos una empresa de desarrollo de software y creamos aplicaciones a medida y software a medida diseñadas para cumplir principios sólidos de arquitectura y facilitar la evolución del producto. Ofrecemos soluciones que integran inteligencia artificial y servicios cloud aws y azure, y contamos con experiencia en ciberseguridad y pentesting para proteger tus activos. Si necesitas un proyecto a medida visita nuestra página de aplicaciones a medida y para iniciativas de IA y transformación con agentes IA y soluciones de ia para empresas consulta nuestra oferta en inteligencia artificial. También trabajamos en servicios inteligencia de negocio y power bi para mejorar la toma de decisiones, automatización de procesos, integración con servicios cloud y estrategias de ciberseguridad que garantizan continuidad y confianza.

Conclusión: Aplicar principios de diseño como SOLID no es solo teoría es una práctica que facilita añadir nuevas funcionalidades como canales de notificación sin romper lo ya construido. En Q2BSTUDIO combinamos buenas prácticas de diseño con tecnologías modernas para entregar software robusto y alineado con objetivos de negocio.

A BREAK?

Play for a moment before you go

OUR SERVICES

How we can help you

Artificial intelligence

AI agents, chatbots, and intelligent assistants that automate tasks and serve your customers 24/7 to improve the efficiency of your business.

More info

Software Development

Web, mobile, and desktop applications, intranets, e-commerce, SaaS, and management platforms designed for your company's specific needs.

More info

Cloud services

Migration, infrastructure, managed hosting, high availability, and security on Microsoft Azure and Amazon Web Services to help your business scale without limits.

More info

Cybersecurity and pentesting

Security audits, penetration testing and protection of applications, data and infrastructure on-premise and cloud, with ethical hacking and regulatory compliance.

More info

Business Intelligence

Dashboards and data analysis with Power BI: we integrate your sources, design dashboards and KPIs and turn your data into decisions.

More info

Process automation

We automate repetitive tasks and connect your applications with n8n, Power Automate, Make, and RPA, eliminating manual work and increasing productivity.

More info

Training for Companies

We train your teams in technology with criteria: web development, databases, Git, best practices and security, automation with n8n, artificial intelligence for companies and creation of AI solutions with Azure AI Foundry.

More info

Code Auditing

We audit the code that you, your team or an AI create: we tell you what is good and what to improve, we secure it and make it ready for production, web or app.

More info

AI Image Generation

We create for you the images that your business needs with artificial intelligence: product, networks, advertising, illustration and avatars. You tell us what you want and we deliver it ready to use.

More info

AI Video Generation

We create videos with artificial intelligence for you: promotional, networking, virtual presenters, dubbing and animations. You tell us the idea and we will deliver it assembled and ready to publish.

More info

AI Conversational Avatars

We create conversational avatars with AI – digital humans with a face and voice – that serve your customers and teams with the knowledge of your company, on your website, interactive monitors, WhatsApp or Teams.

More info

Online Marketing and AI

Google Ads, Meta Ads, LinkedIn Ads and AI Engine Positioning (GEO/AEO): we attract customers and make your brand appear where they search for you, also on ChatGPT, Gemini and Perplexity.

More info

Do you have a project in mind?

Tell us your vision and we'll turn it into a software solution. Whatever the scope, we make your idea real.

Live Chat