SOLID em C#


Por que usar SOLID?
Ideia: cada classe deve ter um único motivo para mudar.
Ruim:
class OrderService { public void PlaceOrder(Order order) { // valida e salva SaveToDb(order); // gera nota var pdf = GenerateInvoice(order); // envia e-mail SendEmail(order.CustomerEmail, pdf); } private void SaveToDb(Order order) { /* ... */ } private byte[] GenerateInvoice(Order order) { /* ... */ return Array.Empty<byte>(); } private void SendEmail(string to, byte[] attachment) { /* ... */ } }
Melhor:
interface IOrderRepository { void Save(Order order); } interface IInvoiceGenerator { byte[] Generate(Order order); } interface IEmailSender { void Send(string to, byte[] attachment); } class OrderService { private readonly IOrderRepository repo; private readonly IInvoiceGenerator invoice; private readonly IEmailSender email; public OrderService(IOrderRepository repo, IInvoiceGenerator invoice, IEmailSender email) { this.repo = repo; this.invoice = invoice; this.email = email; } public void PlaceOrder(Order order) { repo.Save(order); var pdf = invoice.Generate(order); email.Send(order.CustomerEmail, pdf); } }
Ideia: aberto para extensão, fechado para modificação.
Ruim:
class CheckoutService { public decimal Pay(string type, decimal amount) { if (type == "pix") { // lógica Pix } else if (type == "cartao") { // lógica Cartão } else if (type == "boleto") { // lógica Boleto } return amount; } }
Melhor:
interface IPaymentMethod { bool CanHandle(string type); void Pay(decimal amount); } class PixPayment : IPaymentMethod { public bool CanHandle(string type) => type == "pix"; public void Pay(decimal amount) { /* lógica do Pix */ } } class CardPayment : IPaymentMethod { public bool CanHandle(string type) => type == "cartao"; public void Pay(decimal amount) { /* lógica do Cartão */ } } class BoletoPayment : IPaymentMethod { public bool CanHandle(string type) => type == "boleto"; public void Pay(decimal amount) { /* lógica do Boleto */ } } class CheckoutService { private readonly IEnumerable<IPaymentMethod> methods; public CheckoutService(IEnumerable<IPaymentMethod> methods) => this.methods = methods; public void Pay(string type, decimal amount) { var method = methods.First(m => m.CanHandle(type)); method.Pay(amount); } }
Ideia: um subtipo deve poder substituir seu tipo base sem quebrar expectativas.
Antipadrão:
class Bird { public virtual void Fly() { /* voa */ } } class Ostrich : Bird { public override void Fly() { throw new NotSupportedException(); } }
Melhor:
interface IBird { /* membros comuns de aves */ } interface IFlyable { void Fly(); } class Sparrow : IBird, IFlyable { public void Fly() { /* voa */ } } class Ostrich : IBird { // não implementa IFlyable; não quebra expectativas } void MakeItFly(IFlyable f) => f.Fly();
Ideia: clientes não devem depender de métodos que não usam.
Ruim:
interface IMultifuncional { void Print(); void Scan(); void Fax(); } class SimplePrinter : IMultifuncional { public void Print() { /* ok */ } public void Scan() { throw new NotSupportedException(); } public void Fax() { throw new NotSupportedException(); } }
Melhor:
interface IPrinter { void Print(); } interface IScanner { void Scan(); } interface IFax { void Fax(); } class SimplePrinter : IPrinter { public void Print() { /* ok */ } } class OfficeMachine : IPrinter, IScanner, IFax { public void Print() { /* ... */ } public void Scan() { /* ... */ } public void Fax() { /* ... */ } }
Ideia: módulos de alto nível e baixo nível devem depender de abstrações.
Sem DIP:
class RealPaymentGateway { public void Pay(decimal amount) { /* chama API externa */ } } class OrderProcessor { private readonly RealPaymentGateway gateway = new RealPaymentGateway(); public void Process(decimal amount) => gateway.Pay(amount); }
Com DIP:
interface IPaymentGateway { void Pay(decimal amount); } class RealPaymentGateway : IPaymentGateway { public void Pay(decimal amount) { /* chama API externa */ } } class OrderProcessor { private readonly IPaymentGateway gateway; public OrderProcessor(IPaymentGateway gateway) { this.gateway = gateway; } public void Process(decimal amount) => gateway.Pay(amount); }
Registro com Microsoft.Extensions.DependencyInjection:
// using Microsoft.Extensions.DependencyInjection; var services = new ServiceCollection(); services.AddTransient<IPaymentGateway, RealPaymentGateway>(); services.AddTransient<OrderProcessor>(); var sp = services.BuildServiceProvider(); var processor = sp.GetRequiredService<OrderProcessor>(); processor.Process(100m);
Dicas rápidas
Se quiser, eu monto um exemplo .NET minimal com esses trechos prontos para rodar e testar. Quer que eu gere um repositório base?
Aplicar SOLID em C# não precisa ser complicado. Com pequenas mudanças, separar responsabilidades, programar contra interfaces e usar polimorfismo, seu código fica mais limpo, testável e pronto para crescer. Se quiser, posso transformar esses exemplos em um projeto .NET mínimo com testes para você clonar.
Why use SOLID?
Idea: each class should have a single reason to change.
Bad:
class OrderService { public void PlaceOrder(Order order) { // validate and save SaveToDb(order); // generate invoice var pdf = GenerateInvoice(order); // send email SendEmail(order.CustomerEmail, pdf); } private void SaveToDb(Order order) { /* ... */ } private byte[] GenerateInvoice(Order order) { /* ... */ return Array.Empty<byte>(); } private void SendEmail(string to, byte[] attachment) { /* ... */ } }
Better:
interface IOrderRepository { void Save(Order order); } interface IInvoiceGenerator { byte[] Generate(Order order); } interface IEmailSender { void Send(string to, byte[] attachment); } class OrderService { private readonly IOrderRepository repo; private readonly IInvoiceGenerator invoice; private readonly IEmailSender email; public OrderService(IOrderRepository repo, IInvoiceGenerator invoice, IEmailSender email) { this.repo = repo; this.invoice = invoice; this.email = email; } public void PlaceOrder(Order order) { repo.Save(order); var pdf = invoice.Generate(order); email.Send(order.CustomerEmail, pdf); } }
Idea: open for extension, closed for modification.
Bad:
class CheckoutService { public decimal Pay(string type, decimal amount) { if (type == "pix") { // Pix logic } else if (type == "card") { // Card logic } else if (type == "boleto") { // Boleto logic } return amount; } }
Better:
interface IPaymentMethod { bool CanHandle(string type); void Pay(decimal amount); } class PixPayment : IPaymentMethod { public bool CanHandle(string type) => type == "pix"; public void Pay(decimal amount) { /* Pix logic */ } } class CardPayment : IPaymentMethod { public bool CanHandle(string type) => type == "card"; public void Pay(decimal amount) { /* Card logic */ } } class BoletoPayment : IPaymentMethod { public bool CanHandle(string type) => type == "boleto"; public void Pay(decimal amount) { /* Boleto logic */ } } class CheckoutService { private readonly IEnumerable<IPaymentMethod> methods; public CheckoutService(IEnumerable<IPaymentMethod> methods) => this.methods = methods; public void Pay(string type, decimal amount) { var method = methods.First(m => m.CanHandle(type)); method.Pay(amount); } }
Idea: subtypes must be substitutable for their base types without breaking expectations.
Anti-pattern:
class Bird { public virtual void Fly() { /* flies */ } } class Ostrich : Bird { public override void Fly() { throw new NotSupportedException(); } }
Better:
interface IBird { /* common bird members */ } interface IFlyable { void Fly(); } class Sparrow : IBird, IFlyable { public void Fly() { /* flies */ } } class Ostrich : IBird { // does not implement IFlyable; no broken expectations } void MakeItFly(IFlyable f) => f.Fly();
Idea: clients should not be forced to depend on methods they don’t use.
Bad:
interface IMultifunction { void Print(); void Scan(); void Fax(); } class SimplePrinter : IMultifunction { public void Print() { /* ok */ } public void Scan() { throw new NotSupportedException(); } public void Fax() { throw new NotSupportedException(); } }
Better:
interface IPrinter { void Print(); } interface IScanner { void Scan(); } interface IFax { void Fax(); } class SimplePrinter : IPrinter { public void Print() { /* ok */ } } class OfficeMachine : IPrinter, IScanner, IFax { public void Print() { /* ... */ } public void Scan() { /* ... */ } public void Fax() { /* ... */ } }
Idea: high-level and low-level modules should depend on abstractions.
Without DIP:
class RealPaymentGateway { public void Pay(decimal amount) { /* calls external API */ } } class OrderProcessor { private readonly RealPaymentGateway gateway = new RealPaymentGateway(); public void Process(decimal amount) => gateway.Pay(amount); }
With DIP:
interface IPaymentGateway { void Pay(decimal amount); } class RealPaymentGateway : IPaymentGateway { public void Pay(decimal amount) { /* calls external API */ } } class OrderProcessor { private readonly IPaymentGateway gateway; public OrderProcessor(IPaymentGateway gateway) { this.gateway = gateway; } public void Process(decimal amount) => gateway.Pay(amount); }
Registering with Microsoft.Extensions.DependencyInjection:
// using Microsoft.Extensions.DependencyInjection; var services = new ServiceCollection(); services.AddTransient<IPaymentGateway, RealPaymentGateway>(); services.AddTransient<OrderProcessor>(); var sp = services.BuildServiceProvider(); var processor = sp.GetRequiredService<OrderProcessor>(); processor.Process(100m);
Quick tips
Applying SOLID principles in C# doesn't have to be complicated. With small changes, separating responsibilities, programming against interfaces, and using polymorphism, your code becomes cleaner, more testable, and ready to grow. If you want, I can turn these examples into a minimal .NET project with tests for you to clone.