SOLID en la práctica con Python y UML 2025

SOLID 2025: SRP, OCP, LSP, ISP y DIP explicados con ejemplos en Python y UML para software a medida, IA, ciberseguridad y servicios cloud AWS/Azure.

29 ago 2025 • 5 min read • Q2BSTUDIO Team

Inteligencia-Artificial-

Introducción

SOLID no es teoría vacía, es la póliza que evita que odies tu propio código. En este artículo reescribimos y actualizamos los principios SOLID para 2025 con ejemplos en Python y esquemas UML sencillos. Verás ejemplos malos y buenos para SRP, OCP, LSP, ISP y DIP. También explicamos cómo estos principios encajan en proyectos reales de software a medida, aplicaciones a medida e iniciativas avanzadas de inteligencia artificial, ciberseguridad y servicios cloud aws y azure que desarrolla Q2BSTUDIO.

Sobre Q2BSTUDIO

Q2BSTUDIO es una empresa de desarrollo de software especializada en software a medida y aplicaciones a medida. Somos especialistas en inteligencia artificial, ia para empresas, agentes IA, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio y soluciones como power bi. Aplicamos buenas prácticas de diseño como SOLID para reducir bugs, mejorar mantenimiento y acelerar entregas en proyectos de integración de IA, analítica y ciberseguridad.

Principio SRP Single Responsibility Principle

Idea clave SRP: cada módulo o clase debe tener una sola responsabilidad. Evita clases multifunción que mezclan persistencia, lógica de negocio y notificaciones.

Ejemplo malo SRP en Python

class UserService: def __init__(self, db, mailer): self.db = db self.mailer = mailer def create_user(self, user): self.db.insert(user) self.mailer.send_welcome_email(user) def export_users_csv(self, path): users = self.db.get_all() with open(path, 'w') as f: for u in users: f.write(f'{u.id},{u.email}\\n')

Problema: UserService hace persistencia, envío de correo y exportación. Cambiar cualquiera de estas responsabilidades obliga a modificar la misma clase.

Ejemplo bueno SRP en Python

class UserRepository: def __init__(self, db): self.db = db def add(self, user): self.db.insert(user) def get_all(self): return self.db.get_all() class Mailer: def send_welcome_email(self, user): pass class UserExporter: def export_csv(self, users, path): with open(path, 'w') as f: for u in users: f.write(str(u.id) + ',' + u.email + '\\n') class UserService: def __init__(self, repo, mailer): self.repo = repo self.mailer = mailer def create_user(self, user): self.repo.add(user) self.mailer.send_welcome_email(user)

UML SRP simple

[UserService] --> [UserRepository] [UserService] --> [Mailer] [UserExporter] -- separate responsibility

Principio OCP Open Closed Principle

Idea clave OCP: las entidades deben estar abiertas a extensión pero cerradas a modificación. Añade comportamientos sin tocar código probado.

Ejemplo malo OCP en Python

def calculate_discount(order, customer_type): if customer_type == 'regular': return order.total * 0.05 elif customer_type == 'vip': return order.total * 0.15

Problema: cada nuevo tipo de cliente requiere modificar la función.

Ejemplo bueno OCP en Python mediante polimorfismo

class DiscountPolicy: def apply(self, order): raise NotImplementedError class RegularDiscount(DiscountPolicy): def apply(self, order): return order.total * 0.05 class VIPDiscount(DiscountPolicy): def apply(self, order): return order.total * 0.15 def calculate_discount(order, policy: DiscountPolicy): return policy.apply(order)

UML OCP

[DiscountPolicy] <|-- [RegularDiscount] <|-- [VIPDiscount] [Order] --> [DiscountPolicy]

Principio LSP Liskov Substitution Principle

Idea clave LSP: las subclases deben ser sustituibles por sus superclases sin alterar el comportamiento esperado.

Ejemplo malo LSP en Python

class Rectangle: def __init__(self, w, h): self.w = w self.h = h def set_width(self, w): self.w = w def set_height(self, h): self.h = h def area(self): return self.w * self.h class Square(Rectangle): def set_width(self, w): self.w = w self.h = w def set_height(self, h): self.h = h self.w = h

Problema: Square rompe expectativas de Rectangle cuando código cliente cambia width sin prever que height también cambiará.

Ejemplo bueno LSP en Python

class Shape: def area(self): raise NotImplementedError class Rectangle(Shape): def __init__(self, w, h): self.w = w self.h = h def area(self): return self.w * self.h class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side * self.side

UML LSP

[Shape] <|-- [Rectangle] <|-- [Square]

Principio ISP Interface Segregation Principle

Idea clave ISP: prefiera muchas interfaces específicas a una interfaz general que obliga a implementar métodos innecesarios.

Ejemplo malo ISP en Python

class Worker: def work(self): pass def eat(self): pass class Robot(Worker): def work(self): pass def eat(self): raise Exception('no come')

Problema: Robot no puede cumplir eat pero está obligado por la interfaz Worker.

Ejemplo bueno ISP en Python

class Workable: def work(self): raise NotImplementedError class Eatable: def eat(self): raise NotImplementedError class Human(Workable, Eatable): def work(self): pass def eat(self): pass class Robot(Workable): def work(self): pass

UML ISP

[Workable] <|-- [Human] [Eatable] <|-- [Human] [Workable] <|-- [Robot]

Principio DIP Dependency Inversion Principle

Idea clave DIP: dependa de abstracciones, no de implementaciones. Facilita testing, substitución y despliegues en servicios cloud aws y azure cuando integras adaptadores externos.

Ejemplo malo DIP en Python

class MySQLDatabase: def connect(self): pass class UserService: def __init__(self): self.db = MySQLDatabase() def save(self, user): self.db.connect() self.db.insert(user)

Problema: UserService está acoplado a MySQLDatabase.

Ejemplo bueno DIP en Python

class Database: def connect(self): raise NotImplementedError class MySQLDatabase(Database): def connect(self): pass class UserService: def __init__(self, db: Database): self.db = db def save(self, user): self.db.connect() self.db.insert(user)

UML DIP

[UserService] --> [Database] [MySQLDatabase] --|> [Database]

Patrones prácticos y aplicabilidad en proyectos reales

Integrar SOLID con prácticas DevOps, arquitecturas cloud y soluciones de inteligencia artificial mejora la escalabilidad y seguridad. En Q2BSTUDIO aplicamos SOLID en proyectos de software a medida, implementamos microservicios en servicios cloud aws y azure, y diseñamos agentes IA y pipelines de datos compatibles con power bi y servicios inteligencia de negocio. Esto reduce deuda técnica y facilita auditorías de ciberseguridad.

Consejos para equipos

1. Revisiones de código enfocadas en responsabilidades y acoplamiento. 2. Tests que detecten violaciones a LSP y OCP. 3. Documentación UML mínima para comunicar límites de responsabilidad. 4. Usar inyección de dependencias para facilitar deploys en servicios cloud aws y azure y pruebas con mocks en proyectos de inteligencia artificial.

Beneficios para clientes de Q2BSTUDIO

Al aplicar SOLID en soluciones de software a medida, Q2BSTUDIO entrega productos más robustos y mantenibles, reduce tiempo de resolución de incidencias en ciberseguridad, acelera adopción de ia para empresas y mejora la integración con herramientas de inteligencia de negocio y power bi. Nuestras soluciones de agentes IA y servicios de consultoría en inteligencia artificial garantizan modelos modulares y fáciles de evolucionar.

Resumen rápido

SRP separar responsabilidades. OCP extender sin modificar. LSP garantizar sustituibilidad. ISP interfaces específicas. DIP depender de abstracciones. Aplicando estos principios en Python y representándolos con UML ligero se reduce la complejidad en proyectos de software a medida, aplicaciones a medida e iniciativas de inteligencia artificial y ciberseguridad.

Contacta con Q2BSTUDIO

Si buscas un partner para desarrollar software a medida, aplicaciones a medida, soluciones de inteligencia artificial, agentes IA, servicios cloud aws y azure, ciberseguridad o proyectos de servicios inteligencia de negocio con power bi, en Q2BSTUDIO te ayudamos a aplicar SOLID desde la arquitectura hasta los tests.

Palabras clave

aplicaciones a medida, software a medida, inteligencia artificial, ciberseguridad, servicios cloud aws y azure, servicios inteligencia de negocio, ia para empresas, agentes IA, power bi

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