<html>
  <head>
    <title>Needle Manual :: Chapter 1: Introduction</title>
    <link type="text/css" rel="stylesheet" href="manual.css" />
  </head>
  
  <body>
    <div id="banner">
      <table border='0' cellpadding='0' cellspacing='0' width='100%'>
        <tr><td valign='top' align='left'>
          <div class="title">
            <span class="product">Needle&mdash;</span><br />
            <span class="tagline">to the point --></span>
          </div>
        </td><td valign='middle' align='right'>
          <div class="info">
            Needle Version: <strong>0.5.0</strong><br />
            Manual Last Updated: <strong>2004-10-15 03:41 GMT</strong>
          </div>
        </td></tr>
      </table>
    </div>

    <table border='0' width='100%' cellpadding='0' cellspacing='0'>
      <tr><td valign='top'>

        <div id="navigation">
          <h1>Needle Manual</h1>

          <h2>Chapters</h2>
          <ol type="I">
          
            <li><strong>
                <a href="chapter-1.html">
                Introduction
                </a>
                </strong> <big>&larr;</big>
              <ol type="1">
                
                  <li><a href="chapter-1.html#s1">What is Needle?</a></li>
                
                  <li><a href="chapter-1.html#s2">How Can It Help Me?</a></li>
                
                  <li><a href="chapter-1.html#s3">License Information</a></li>
                
                  <li><a href="chapter-1.html#s4">Support</a></li>
                
              </ol>
            </li>
          
            <li>
                <a href="chapter-2.html">
                Registry
                </a>
                
              <ol type="1">
                
                  <li><a href="chapter-2.html#s1">Overview</a></li>
                
                  <li><a href="chapter-2.html#s2">Creating</a></li>
                
                  <li><a href="chapter-2.html#s3">Services</a></li>
                
                  <li><a href="chapter-2.html#s4">Namespaces</a></li>
                
              </ol>
            </li>
          
            <li>
                <a href="chapter-3.html">
                Dependency Injection
                </a>
                
              <ol type="1">
                
              </ol>
            </li>
          
            <li>
                <a href="chapter-4.html">
                Interceptors
                </a>
                
              <ol type="1">
                
              </ol>
            </li>
          
            <li>
                <a href="chapter-5.html">
                Service Models
                </a>
                
              <ol type="1">
                
              </ol>
            </li>
          
            <li>
                <a href="chapter-6.html">
                Logging
                </a>
                
              <ol type="1">
                
              </ol>
            </li>
          
            <li>
                <a href="chapter-7.html">
                Creating Libraries
                </a>
                
              <ol type="1">
                
              </ol>
            </li>
          
          </ol>

          <h2>API Reference</h2>

          <ul>
            <li><a href="http://needle.rubyforge.org/api/index.html">Needle API</a></li>
          </ul>

          <h2>Tutorials</h2>
          <ol>
          
          </ol>

          <p align="center"><strong>More To Come...</strong></p>

          <div class="license">
            <a href="http://creativecommons.org/licenses/by-sa/2.0/"><img alt="Creative Commons License" border="0" src="http://creativecommons.org/images/public/somerights" /></a><br />
            This manual is licensed under a <a href="http://creativecommons.org/licenses/by-sa/2.0/">Creative Commons License</a>.
          </div>
        </div>

      </td><td valign='top' width="100%">

        <div id="content">

          <h1>1. Introduction</h1>



     <h2>
       <a name="s1"></a>
       1.1. What is Needle?
     </h2>

   

   <div class="section">
     <p>Needle is a dependency injection (also, inversion of control) container for <a href="http://www.ruby-lang.org">Ruby</a>.<br />
</p>
   </div>



     <h2>
       <a name="s2"></a>
       1.2. How Can It Help Me?
     </h2>

   

   <div class="section">
     <p>So, what can Needle do for you? Ultimately, it can reduce the amount of code that you have to write, simplifying many common programming tasks for you. This has the two-fold benefit of both decreasing application development time, and of decreasing the effort needed to maintain your application.</p>

	<p>But what, <em>specifically</em>, can Needle do for you?</p>

	<p>Try these on for size:</p>

	<ul>
	<li><a href="#logexec">Log Method Execution</a></li>
		<li><a href="#refsvc">Reference Another Service</a></li>
		<li><a href="#unittest">Unit Testing</a></li>
		<li><a href="#lifecycle">Lifecycle Management</a></li>
	</ul>

	<p>(Thanks to Howard Lewis Ship for his <a href="http://jakarta.apache.org/hivemind">HiveMind</a> documentation, from which some of the above bullet points were adapted.)</p>

	<h3>Log Method Execution <a name="#logexec"></a></h3>

	<p>Needle has an integrated logging framework, and the ability to log execution trace information without modifying a single line of code in your classes. This means that you can easily see what methods get called, with what arguments, and what the return values are, all without having to physically modify any of your classes.</p>

	<p>Consider the following code, demonstrating how this would be done without Needle:</p>

<pre>
  def foo( arg1, arg2 )
    @log.debug( "in foo with #{arg1} and #{arg2}" ) if @log.debug?
    ...
    result = the_result_of_the_method
    @log.debug( "finishing foo with #{result}" ) if @log.debug
    return result
  rescue Exception =&gt; e
    @log.debug( "foo raised exception #{e.message} (#{e.class})" ) if @log.debug?
    raise
  end
</pre>

	<p>Now, multiply that by the number of methods in your class&#8230; the logging messages quickly overpower the rest of the code, and detract from the flow of your program. This makes your program harder to debug, test, and maintain.</p>

	<p>Now, consider the same method using Needle&#8217;s integrated logging framework&#8230;</p>

<pre>
  def foo( arg1, arg2 )
    ...
    return the_result_of_the_method
  end
</pre>

	<p>Then, when you define the service that you want to add the logging to:</p>

<pre>
  registry.register( :service_name_here ) { |reg| ... }
  registry.intercept( :service_name_here ).with! { logging_interceptor }
</pre>

	<p>That&#8217;s right. There&#8217;s no explicit logging code in there. Instead, you just tell Needle that the methods of the class should be logged, and away it goes. This has the added benefit of allowing your objects to be unit tested, without spewing log messages everywhere.</p>

	<h3>Reference Another Service <a name="#refsvc"></a></h3>

	<p>Invariably in a large application services will reference other services. This is typically accomplished through something like this:</p>

<pre>
  class Component
    ...
    def foo( parms )
      @service ||= lookup_service
      @service.do_something( parms )
    end

    def lookup_service
      ...
    end
    ...
  end
</pre>

	<p>Whether the lookup is done lazily, as shown above, or when the class is first instantiated is irrelevant. The point is that you either have to implement a bunch of code to look up a service based on some criteria, or you hard code the class of the service (which creates tight coupling and makes things like unit testing harder).</p>

	<p>With Needle, you just declare a setter for the service, and then tell Needle that the class depends on the other service:</p>

<pre>
  class Component
    attr_writer :service
    ...
    def foo( parms )
      @service.do_something( parms )
    end
    ...
  end

  registry.register( :component ) do |reg| 
    c = Component.new
    c.service = reg.some_other_service
    c
  end
</pre>

	<p>Then, when your service is instantiated, Needle will automatically look for and instantiate the dependencies for you. This makes for cleaner code, and looser coupling between services.</p>

	<h3>Unit Testing <a name="#unittest"></a></h3>

	<p>Large applications can prove troublesome to unit test exhaustively, especially if there is any kind of tight coupling between components. Such coupling of components can make it difficult to test them separately.</p>

	<p>Needle, by its very nature, encourages loose coupling of components. Also, because dependencies are never instantiated in code, but are instead accepted via setters or constructor arguments, it is trivial to replace those dependencies with mock objects at unit test time.</p>

	<p>Consider this tightly coupled example:</p>

<pre>
  def foo( args )
    @some_dependency ||= MyNewDependency.new
    @some_dependency.do_something(args)
  end
</pre>

	<p>It is impossible to test the method <code>#foo</code> without also testing the MyNewDependency class. However, if the <code>@some_dependency</code> object is made a property that is set externally, you can replace it at test time with a blank:</p>

<pre>
  attr_writer :some_dependency

  def foo( args )
    @some_dependency.do_something( args )
  end
</pre>

	<p>The unit test would become something like this:</p>

<pre>
  def test_foo
    @obj.some_dependecy = MyMockDependency.new
    @obj.foo( args )
    assert @obj.is_in_some_state
  end
</pre>

	<h3>Lifecycle Management <a name="#lifecycle"></a></h3>

	<p>Singleton objects are a fact of life in complex systems. The singleton design pattern is powerful and useful. However, using the Singleton mixin, or declaring methods at the class level, can make your code difficult to unit test since the state of such objects cannot be easily reset.</p>

	<p>Needle has a solution. You can tell Needle to treat a service as either a <em>prototype</em> service (meaning it will be instantiated every time you ask for it, like calling <code>#new</code>), or a <em>singleton</em> service (meaning it will only be instantiated once, and the same instance will be returned for subsequent requests).</p>

	<p>Your object is still just a plain ol&#8217; ordinary Ruby object, but Needle has effectively transformed it into a singleton. This means you can unit test it as if it were nothing special, but when it is used in your application it will act like a singleton.</p>

	<p>Lifecycle management also means that you can control <em>when</em> a service is instantiated.  The <em>prototype</em> and <em>singleton</em> models will always be instantiated as soon as they are requested. Sometimes, though, you don&#8217;t want that&#8212;you&#8217;d like the instantiation to be deferred as late as possible.</p>

	<p>With Needle, you can indicate that a service should use deferred instantiation. This will cause the service to not actually be instantiated until a method is actually invoked on it.  Using this model, you can have services depend on themselves, or other forms of cyclical dependencies.</p>
   </div>



     <h2>
       <a name="s3"></a>
       1.3. License Information
     </h2>

   

   <div class="section">
     <p>Needle is made available under either the <span class="caps">BSD</span> license, or the same license Ruby (which, by extension, also allows the <span class="caps">GPL</span> as a permissable license as well). You can view the full text of any of these licenses in the <code>doc</code> subdirectory of the Needle distrubtion. The texts of the <span class="caps">BSD</span> and <span class="caps">GPL</span> licenses are also available online: <a href="http://www.opensource.org/licenses/bsd-license.php">BSD</a> and <a href="http://www.opensource.org/licenses/gpl-license.php">GPL</a>.</p>

	<p>This manual (in any form, be it source or otherwise) and the scripts and templates used to generate it, are all distributed under the <a href="http://creativecommons.org">Creative Commons</a> <a href="http://creativecommons.org/licenses/by-sa/2.0">Attribution-ShareAlike</a> license.</p>

	<p>If you desire permission to use either Needle or the manual in a manner incompatible with these licenses, please contact the copyright holder (<a href="mailto:jgb3@email.byu.edu">Jamis Buck</a>) in order to negotiate a more compatible license.<br />
</p>
   </div>



     <h2>
       <a name="s4"></a>
       1.4. Support
     </h2>

   

   <div class="section">
     <p>Mailing lists, bug trackers, feature requests, and public forums are available (courtesy of <a href="http://rubyforge.org">RubyForge</a>) at Needle&#8217;s RubyForge project page. Just direct your browser to <a href="http://rubyforge.org/projects/needle">http://rubyforge.org/projects/needle</a>.<br />
</p>
   </div>




        </div>

      </td></tr>
    </table>
  </body>
</html>