Single Responsibility Principle(SRP)
Kanuni hii inasema kwamba kila darasa linapaswa kuwa na jukumu moja. Inasisitiza kwamba darasa linapaswa kufanya kazi moja maalum na lisiwe na sababu nyingi za kubadilika.
Mfano: Kusimamia maelezo ya mtumiaji na kutuma arifa za barua pepe.
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)
Kanuni hii inahimiza kupanua utendakazi kwa kuongeza msimbo mpya badala ya kurekebisha msimbo uliopo.
Mfano: Kushughulikia mbinu tofauti za malipo katika programu ya biashara ya mtandaoni.
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)
Kanuni hii inadai kuwa vipengee vya darasa linalotokana vinapaswa kubadilishwa kwa vitu vya darasa la msingi bila kuathiri usahihi wa programu.
Mfano: Kusimamia maumbo ya kijiometri.
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)
Kanuni hii inashauri kuvunja miingiliano kuwa ndogo ili kuzuia kulazimisha madarasa kutekeleza njia ambazo hazihitaji.
Mfano: Violesura vya kusasisha na kuonyesha 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)
Kanuni hii inapendekeza kutumia sindano ya utegemezi kudhibiti utegemezi.
Mfano: Kutumia sindano ya utegemezi kudhibiti utegemezi.
class OrderProcessor
def initialize(db_connection, email_service)
@db_connection = db_connection
@email_service = email_service
end
end
Kumbuka kwamba kutumia SOLID kanuni ndani Ruby kunapaswa kufanywa kwa urahisi kulingana na madhumuni mahususi ya mradi wako na uelewa wako wa SOLID na Ruby.