Nerapake SOLID Prinsip ing Ruby: 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  
  def create_user(user_data)  
    # Logic for creating a user  
  end  
end  
  
class EmailService  
  def send_email(email_data)  
    # Logic for sending an email  
  end  
end  

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.

class PaymentProcessor  
  def process_payment  
    # Common logic for payment processing  
  end  
end  
  
class CreditCardPaymentProcessor < PaymentProcessor  
  def process_payment  
    # Logic for processing credit card payment  
  end  
end  
  
class PayPalPaymentProcessor < PaymentProcessor  
  def process_payment  
    # Logic for processing PayPal payment  
  end  
end  

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.

class Shape  
  def area  
    # Common logic for calculating area  
  end  
end  
  
class Rectangle < Shape  
  def area  
    # Logic for calculating area of rectangle  
  end  
end  
  
class Square < Shape  
  def area  
    # Logic for calculating area of square  
  end  
end  

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.

module UpdateableFeature  
  def update_feature  
    # Logic for updating feature  
  end  
end  
  
module DisplayableFeature  
  def display_feature  
    # Logic for displaying feature  
  end  
end  

Dependency Inversion Principle(DIP)

Prinsip iki nyaranake nggunakake injeksi dependensi kanggo ngatur dependensi.

Conto: Nggunakake injeksi dependensi kanggo ngatur dependensi.

class OrderProcessor  
  def initialize(db_connection, email_service)  
    @db_connection = db_connection  
    @email_service = email_service  
  end  
end  

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