Skip to content

Instantly share code, notes, and snippets.

@richmolj
Last active December 18, 2015 17:59
Show Gist options
  • Save richmolj/5822934 to your computer and use it in GitHub Desktop.
Save richmolj/5822934 to your computer and use it in GitHub Desktop.
Step-by-step refactoring
# 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
@ljsc
Copy link

ljsc commented Jun 20, 2013

I don't think anything is tied to the database, I don't show #save's implementation and I'm never specifying ActiveRecord.

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.

Still, we can change this example to pass something other than a boolean tied to post. I think the central point still I was making works in any case, or no?

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment