Dans un précédent article j’ai évoqué le premier principe S.O.L.I.D (Responsabilité unique).
N’hésitez pas a découvrir les autres principes SOLID dans cette série d’articles:
Maintenant je vous propose une explication pour le deuxième principe S.O.L.I.D, c’est le principe «Ouvert-Fermé» (Open/Closed), ce principe affirme qu’une classe doit être à la fois ouverte à l’extension et fermée à la modification.
Je vous donne un exemple:
public enum PaymentMethod
{
VisaCard = 1,
MasterCard = 2,
Cash = 3,
}
public class PaymentService
{
public PaymentMethod PaymentMethod { get; set; }
public void ProcessPayment()
{
if (PaymentMethod == PaymentMethod.VisaCard)
{
// Some implementation heren
}
else if (PaymentMethod == PaymentMethod.MasterCard)
{
// Some implementation heren
}
else if (PaymentMethod == PaymentMethod.Cash)
{
// Some implementation here
}
// Some implementation here
}
}
Le code est incorrect car il est ouvert à la modification, si un nouveau mode de paiement est ajouté, la classe doit être modifiée.
public interface IPaymentMethod
{
void ProcessPayment();
}
public sealed class VisaCardPayment : IPaymentMethod
{
public void ProcessPayment()
{
// Some implementation here (VisaCardPayment)
}
}
public sealed class MasterCardPayment : IPaymentMethod
{
public void ProcessPayment()
{
// Some implementation here (MasterCardPayment)
}
}
public sealed class CashPayment : IPaymentMethod
{
public void ProcessPayment()
{
// Some implementation here (CashPayment)
}
}
public class PaymentService
{
public PaymentService(IPaymentMethod paymentMethod)
{
PaymentMethod = paymentMethod;
}
private IPaymentMethod PaymentMethod { get; }
public void ProcessPayment()
{
// Some implementation here
PaymentMethod.ProcessPayment();
// Some implementation here
}
}
Le code est correct car si un nouveau mode de paiement est ajouté, la classe n’est pas modifiée.
Si vous avez aimé cet article, n’hésitez pas à le partager !