Last active
December 18, 2015 17:59
-
-
Save richmolj/5822934 to your computer and use it in GitHub Desktop.
Step-by-step refactoring
This file contains hidden or 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
# First iteration | |
class Post | |
def publish | |
self.published_at = Time.now | |
save | |
end | |
end | |
# Second iteration | |
# published_at logic gets more complex | |
class PublishTime | |
def initialize(special_timing) | |
@special_timing = special_timing | |
end | |
def stamp | |
if @special_timing | |
Time.now * 100 - 365 | |
else | |
Time.now | |
end | |
end | |
end | |
class Post | |
def publish | |
publish_time = PublishTime.new(self.special_timing?) | |
self.published_at = publish_time.stamp | |
save | |
end | |
end | |
# Iteration 3 - lots of different timings | |
# We figure out the strategy at runtime | |
# DI! | |
class Post | |
def publish(time = PublishTime.new) | |
time.special_timing = self.special_timing? | |
self.published_at = time | |
save | |
end | |
end | |
# PublishTimeFactory: wysiwyg ok? | |
class PostController | |
def create | |
post = Post.new(params[:post]) | |
PublishTimeFactory.for(post, rand(9)) | |
post.publish(time) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sure, I guess that's just what I assumed based on the fact that there was no implementation shown for
Post#special_timing?
. But I think the point still stands, if that was coming from the database, then this would be an example where I would not use DI. I'm not sure if that's helpful.I guess the central point I'm trying to make is that DI is just a tool. The important thing is that we encourage code that is easily extensible by adding additional objects/classes not by modifying ones that already exist. Especially as we endeavor to make code reuse more of a goal. If we don't we're going to be walking into a whole boatful of prod errors.