Created
August 11, 2013 19:59
-
-
Save blackheaven/6206616 to your computer and use it in GitHub Desktop.
Some thoughts on OOP principles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Ctrl | |
def close | |
user = User.new # load from somewhere | |
CloseAccountPolicy.new(user).apply! | |
puts user.inspect | |
end | |
end | |
# Nearly an AnemicDomainModel because some of it's behavor is externalized | |
class User | |
def initialize | |
@open = true | |
end | |
def open? | |
@open | |
end | |
def close! | |
@open = false | |
end | |
end | |
class CloseAccountPolicy | |
def initialize(user) | |
@user = user | |
end | |
def apply! | |
if @user.open? # Violate Tell don't ask | |
@user.close! | |
send_notification! | |
end | |
end | |
def send_notification! | |
puts "Notification sent!" | |
end | |
end | |
puts Ctrl.new.close |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Ctrl | |
def close | |
user = User.new # load from somewhere | |
CloseAccountPolicy.new(user).apply! | |
puts user.inspect | |
end | |
end | |
# SRP : OK | Non-Anemic | All behavior at the same place | |
class User | |
def initialize | |
@open = true | |
end | |
def close!(&block) | |
@open = false | |
block.call if block # Trigger system/Observer DP | |
end | |
end | |
class CloseAccountPolicy | |
def initialize(user) | |
@user = user | |
end | |
def apply! | |
@user.close! do # Tell don't ask : OK! | |
send_notification! | |
end | |
end | |
def send_notification! | |
puts "Notification sent!" | |
end | |
end | |
puts Ctrl.new.close |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Ctrl | |
def close | |
user = User.new # load from somewhere | |
user.close! | |
puts user.inspect | |
end | |
end | |
# SRP : All the behavior is here but it coupled too all the system parts | |
class User | |
def initialize | |
@open = true | |
end | |
def close! | |
if @open | |
@open = false | |
send_notification! | |
end | |
end | |
def send_notification! | |
puts "Notification sent!" | |
end | |
end | |
puts Ctrl.new.close |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment