advertisement
javaboutique
Search Tips
Articles  |   Tutorials  |   Reviews  |   Tools  |   by Category  |   by Date  |   by Name  |   Submit  |   Source  |   Forums  |  
javaboutique
Browse DevX


Partners & Affiliates











advertisement

Tutorials : Inversion of Control: A Mechanism for Highly Flexible Applications :

There's Always Another Way: Dependency Lookup

UInstead of passing the reference of another object through the constructor, you can use Java Bean properties to set the same. The next code example shows a modified class A, which uses a bean property-based IoC.

Class A {
  private B b;
  
  public A(){
  }

  public setB(B b) {
       this.b = b;
  }

  public void doSomething(){
    
      b.someMethod();
  }
As you may have realised, the fundamental idea behind IoC is to completely decouple objects from explicit dependency. In IoC, one object exposes its dependency to other objects through a defined contract in terms of a constructor or bean property.

There is another way to decouple the objects: dependency lookup. This is implemented as a Service Locator pattern. In dependency lookup, the dependent object explicitly performs a look-up for the required Service objects. By doing so, the Service Locator can return various versions and flavors of the required Service objects. Thus, the dependent object does not need to use any explicit reference to any implementation of the Service object. However, the dependent object still needs to know about the Service Locator component.

Tightening a Few Bolts

In the last two code examples, it's best if B is an interface as opposed to a concrete class. This provides you with the complete flexibility to inject any implementation of the interface B. If B is a concrete class, then you're tied to a particular implementation of a service object.

Comparing the Two Methods

So far, you've seen two methods of passing the dependency to the object: one through constructors and the other through appropriate setter methods. As usual, both methods have their pros and cons.

Here's the advantages of using the constructor-based IoC:

  • You can hide (or encapsulate) all your fields without having to expose them through setter methods. This is important because if you don't want something to change, youneed to make sure you haven't provided it any way to change.
  • A constructor with a specific number of parameters gives you a clear indication of what it means to create an object.
On the other hand, the disadvantages with constructor-based IoC are:
  • If you've got too many parameters to be passed inside the constructor, it starts looking messy.
  • The order of parameters becomes important.
  • If, at the time of creating the object, you are not sure about the dependencies the object will take up, you may not be able to inject the dependency through a constructor.
  • Constructors can suffer from classic inheritance problems when super class constructors do change or a sub-class is added. (LINK TO MY INHERITANCE VS COMPOSITION ARTICLE). Although, this is more of a problem in the OO domain, it is significant enough here to effect the success of IOC.
The dependency lookup concept works fine, but only if all the application modules are developed under the same hood and you have a thorough knowledge of every API of every component used in the application. If you're developing a component for a third party, you're probably not going to know anything about the kind of service locator component that third party will use. Hence, this model might fail to work.

Examples of IOC in Real-life

J2EE containers use IoC to a great extent. The reason for this is clear—containers do not know beforehand about which dependencies between modules are deployed. Somehow, they have to resolve these dependencies at runtime. The containers use both constructor- and setter-based IoC methods discussed above.

PicoContainers promotes constructor injection over setter injection and the Spring framework promotes setter injection over constructor injection. Both of them support both types of IoC.

Code or Configuration

You've seen that the fundamental goal of IoC is to achieve decoupling between two separate objects. You inject the dependency at some stage, typically using a top-level assembler component. Now, this assembler component obviously needs to know the dependencies before it can inject the correct onesto the various objects.

At this stage, the dependencies have been coded into the assembler component (the revolutionists call this hard-coding) or the assembler component is looking at some configuration file to determine the dependencies.

If an application is potentially going to be used in various types of containers, having a configuration file (typically XML) is the most flexible. A familiar example would be EJBs in J2EE containers. On the other hand, components with relatively static dependencies might also be glued programmatically inside the assembler component.

Some complain that with programmatic configuration, you have to recompile the code for any change in the dependencies. The basic points of IoC and decoupling have melted away as if you knew the dependency beforehand—then why would youneed decoupling?

The point is that the design of the application should sustain the test of time and that means it must be scalable. Decoupling and IoC are the best techniques to achieve this. You can always compromise on how the machine should be operated and not on the design of the machine itself.

More Flexibility with Less Re-engineering

IoC is a powerful technique you can use to achieve a highly decoupled system in whichan application can be assembled by gluing different service components in a configurable manner. No doubt, this leads to a very flexible application, which can be tailored to different environments with minimum re-engineering. You all know that anything that means less cost and fat pockets will this will be popular with managers. So friends, let's invert the control.

References:

How to Add Java Applets to Your Site

New on the Java Boutique:

New Review:

Time Management Made Easy with the Quartz Enterprise Job Scheduler
Why not just use the Java timer API? This open source scheduling API boasts simplicity, ease-of-integration, a well-rounded feature set, and it's free!

New Applet:

Reverse Complement
Reverse Complement is a simple applet that converts DNA or RNA sequences into three useful formats.

Elsewhere on internet.com:

WebDeveloper Java
Lots of Java information on webdeveloper.com

WDVL Java
Thorough Java resource at the Web Developer's Virtual Library.

ScriptSearch Java
Hundreds of free Java code files to download.

jGuru: Your View of the Java Universe
Customizable portal with online training, FAQs, regular news updates, and tutorials.

 Intel Go Parallel Portal
 Internet.com eBook Library
 IBM Software Construction Toolbox
 Microsoft RIA Development Center
 Destination .NET
XML error: not well-formed (invalid token) at line 43
advertisement
Receive Articles via our XML/RSS feed
Receive Articles via our XML/RSS feed

JavaBytes
Internet Cyclone
This powerful, easy-to-use, internet optimizer is for Windows 95, 98, ME, NT, 2000 and XP. It's designed to automatically optimize your Windows settings, boosting your Internet connection up to 200%.

Remember Figlets? They're Back With Zend
Microsoft Readies an App Store Competitor?
Google: Chrome Browser Will Make Money
Sam Ramji: Microsoft's Man in Open Source
Google to Shake Up Browsers With Own Launch
Mozilla's Ubquity Mashup: For The Masses?
iPhone Users Just Want to Have Fun
Oops! I Fixed the Linux Kernel
Jim Zemlin: The New Center of Linux Gravity
Microsoft's Novell Investment Tops $340M

Writing Functional Code with RDFa
BitLocker Brings Encryption to Windows Server 2008
Network Know-How: Exploring Network Algorithms
Create a Durable and Reliable WCF Service with MSMQ 4.0
The Baker's Dozen: 13 Tips for SQL Server 2008 and SSRS 2008
Book Excerpt: Microsoft Expression Blend Unleashed
Develop a Mobile RSS Feed the Easy Way
State of the Semantic Web: Know Where to Look
A 3D Exploration of the HTML Canvas Element
Setting Up and Running Subversion and Tortoise SVN with Visual Studio and .NET

Advertising Info  |   Member Services  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Intel PDF: Virtualization Delivers Data Center Efficiency
Intel eBook: Managing the Evolving Data Center
Microsoft Article: BitLocker Brings Encryption to Windows Server 2008
Symantec eBook: The Guide to E-Mail Archiving and Management
Microsoft Article: RODCs Transform Branch Office Security
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
Avaya Article: Advancing the State of the Art in Customer Service
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Avaya Article: Avaya AE Services Provide Rapid Telephony Integration with Facebook
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Seminar: Efficiencies in Hardware/Software Virtualization
HP Webcast: Disaster Recovery Planning
Go Parallel Video: Performance and Threading Tools for Game Developers
HP Video: StorageWorks EVA4400 and Oracle
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
IBM TCO eKIT: Your IT Budget is Under Attack, Get in Control
IBM Energy Efficiency eKIT: Learn How to Reduce Costs
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt and free High-Performance SQL Code eBook
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
Microsoft Article: Silverlight Streaming--Free Video Hosting for All
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
HP Demo: StorageWorks EVA4400
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES