Single Responsibility Principle(SRP)
Prinsip iki nyatakake yen saben kelas kudu nduweni tanggung jawab siji. Iku nandheske sing kelas kudu nindakake siji fungsi tartamtu lan ora duwe kakehan alasan kanggo ngganti.
Conto: Ngatur informasi pangguna lan ngirim kabar email.
class UserManager {
public void CreateUser(UserData userData) {
// Logic to create a user
}
}
class EmailService {
public void SendEmail(EmailData emailData) {
// Logic to send an email
}
}
Open/Closed Principle(OCP)
Prinsip iki nyengkuyung nambah fungsi kanthi nambah kode anyar tinimbang ngowahi kode sing wis ana.
Conto: Nangani macem-macem cara pembayaran ing aplikasi e-commerce.
abstract class PaymentProcessor {
public abstract void ProcessPayment();
}
class CreditCardPaymentProcessor: PaymentProcessor {
public override void ProcessPayment() {
// Logic to process credit card payment
}
}
class PayPalPaymentProcessor: PaymentProcessor {
public override void ProcessPayment() {
// Logic to process PayPal payment
}
}
Liskov Substitution Principle(LSP)
Prinsip iki negesake manawa obyek saka kelas asale kudu bisa diganti kanggo obyek kelas dasar tanpa mengaruhi akurasi program kasebut.
Tuladha: Ngatur wangun geometris.
abstract class Shape {
public abstract double CalculateArea();
}
class Rectangle: Shape {
public override double CalculateArea() {
// Logic to calculate area of rectangle
}
}
class Square: Shape {
public override double CalculateArea() {
// Logic to calculate area of square
}
}
Interface Segregation Principle(ISP)
Prinsip iki menehi saran supaya antarmuka rusak dadi luwih cilik supaya ora meksa kelas kanggo ngetrapake metode sing ora dibutuhake.
Conto: Antarmuka kanggo nganyari lan nampilake data.
interface IUpdateableFeature {
void UpdateFeature();
}
interface IDisplayableFeature {
void DisplayFeature();
}
Dependency Inversion Principle(DIP)
Prinsip iki nyaranake nggunakake injeksi dependensi kanggo ngatur dependensi.
Conto: Nggunakake injeksi dependensi kanggo ngatur dependensi.
class OrderProcessor {
private readonly DBConnection _dbConnection;
private readonly EmailService _emailService;
public OrderProcessor(DBConnection dbConnection, EmailService emailService) {
_dbConnection = dbConnection;
_emailService = emailService;
}
}
Elinga yen ngetrapake SOLID prinsip ing C # kudu ditindakake kanthi fleksibel adhedhasar tujuan spesifik proyek sampeyan lan pemahaman sampeyan SOLID lan C #.