-
-
Save mynameisrufus/5471536 to your computer and use it in GitHub Desktop.
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
### Problem, rigid dependency injection ### | |
class Demo | |
def initialize | |
@instancev = Something.new | |
end | |
def method_1 | |
do_that | |
@instancev.something | |
end | |
def method_2 | |
filter_something | |
@instancev.orother | |
end | |
end | |
### Solution (Factory method) ### | |
class Demo | |
def something | |
Something | |
end | |
def will_use_something | |
s = something.new | |
s.awesome_stuff | |
end | |
# `will_use_something` has no side effects | |
def change_something_state | |
s = somthing.new.mutate | |
s.awesome_stuff | |
end | |
end | |
### Solution (Singleton method) ### | |
class Demo | |
def something | |
@something ||= Something.new | |
end | |
def will_use_something | |
something.awesome_stuff | |
end | |
# Side effects as `will_use_something` might return something else now. | |
def change_something_state | |
something.mutate! | |
end | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment