"Em outras palavras, todas as classes complicadas devem ser divididas em classes menores, responsáveis por um comportamento específico, facilitando o entendimento e a manutenção da base de código." https://rubygarage.org/blog/solid-principles-of-ood
Probably the most well known principle, and one that should try to adhere to most of the time.
Let's say you have this code:
class AuthenticatesUser
def authenticate(email, password)
if matches?(email, password)
do_some_authentication
else
raise NotAllowedError
end
end
private
def matches?(email, password)
user = find_from_db(:user, email)
user.encrypted_password == encrypt(password)
end
end
The AuthenticatesUser
class is responsible for authenticating the user as well as knowing if the email and password match the ones in the database. It has two responsibilities, and according to the principle it should only have one, let's extract one.
class AuthenticatesUser
def authenticate(email, password)
if MatchesPasswords.new(email, password).matches?
do_some_authentication
else
raise NotAllowedError
end
end
end
class MatchesPasswords
def initialize(email, password)
@email = email
@password = password
end
def matches?
user = find_from_db(:user, @email)
user.encrypted_password == encrypt(@password)
end
end
I've used a refactoring technique called Extract Class and then use it on the class I already had, this is called sharing behaviour through composition.