NeedHELPASAP

25 views
Skip to first unread message

Joener Preagola

unread,
May 12, 2014, 2:09:26 AM5/12/14
to rubyonra...@googlegroups.com
Im not familiar on dependency injection

Remove Car's explicit reference to Engine by using dependency injection.

class Car
  attr_reader :engine

  def engine
    @engine ||= Engine.new(4)
  end

  def move
    engine.accelerate
  end
end

class Engine
  attr_reader :cylinders

  def initialize(cylinders)
    @cylinders = cylinders
  end

  def accelerate

  end
end



Matt Jones

unread,
May 13, 2014, 8:50:30 AM5/13/14
to rubyonra...@googlegroups.com


On Monday, 12 May 2014 02:09:26 UTC-4, Joener Preagola wrote:
Im not familiar on dependency injection

Remove Car's explicit reference to Engine by using dependency injection.


Posting homework / exercise questions verbatim is generally frowned upon on most mailing lists. A better start might be "here's what I've tried, and here's what's going wrong", or "here's what I've found in research but it doesn't make sense".

In this specific case, you may want to consider other ways that Car could get an Engine object besides constructing it explicitly in Car#engine. Maybe pass it in as an argument, or change the attr_reader to an attr_accessor and directly write it? Also consider splitting the "how" (the class to be constructed) from the "what" (the parameters passed to the constructor).

--Matt Jones

Robert Walker

unread,
May 13, 2014, 12:03:27 PM5/13/14
to rubyonra...@googlegroups.com
Joener Preagola wrote in post #1145843:
> Im not familiar on dependency injection
>
> Remove Car's explicit reference to Engine by using dependency injection.

The first question to ask yourself is, "Why is it important to use
dependency injection in this specific scenario?"

After all this is Ruby, not some lame statically typed language like
Java or something. In Java Dependency Injection (DI) is uses to solve a
lots of issues that are mostly due to limitations of the language
itself. In fact it requires looking outside of the language itself to
even support DI (i.e. XML configuration files or Java annotations).

There's a tendency to make DI sound like something magical or
complicated in the Java world, but in Ruby (and other dynamically typed
languages) you won't here much about it. Mostly because it's a really
simple concept with a really simple implementation.

--
Posted via http://www.ruby-forum.com/.
Reply all
Reply to author
Forward
0 new messages