-
-
Save richmolj/5822934 to your computer and use it in GitHub Desktop.
| # 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 |
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.
I don't think anything is tied to the database, I don't show #save's implementation and I'm never specifying ActiveRecord.
I wouldn't call a DI or non-DI solution better or worse in this case. 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?