Nerapake SOLID Prinsip ing Java: Tuladha lan Praktek Paling Apik

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 {  
  void createUser(UserData userData) {  
    // Logic for creating a user  
  }  
}  
  
class EmailService {  
  void sendEmail(EmailData emailData) {  
    // Logic for sending 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 {  
  abstract void processPayment();  
}  
  
class CreditCardPaymentProcessor extends PaymentProcessor {  
  void processPayment() {  
    // Logic for processing credit card payment  
  }  
}  
  
class PayPalPaymentProcessor extends PaymentProcessor {  
  void processPayment() {  
    // Logic for processing 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 {  
  abstract double area();  
}  
  
class Rectangle extends Shape {  
  double area() {  
    // Logic for calculating area of rectangle  
  }  
}  
  
class Square extends Shape {  
  double area() {  
    // Logic for calculating area of square  
  }  
}  

Prinsip Segregasi Antarmuka(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 UpdateableFeature {  
  void updateFeature();  
}  
  
interface DisplayableFeature {  
  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 final DBConnection dbConnection;  
  private final EmailService emailService;  
  
  OrderProcessor(DBConnection dbConnection, EmailService emailService) {  
    this.dbConnection = dbConnection;  
    this.emailService = emailService;  
  }  
}  

Elinga yen ngetrapake SOLID prinsip Java kudu ditindakake kanthi fleksibel adhedhasar tujuan spesifik proyek sampeyan lan pangerten babagan SOLID lan Java.