aspose file tools*
The moose likes Beginning Java and the fly likes Loose Coupling Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Loose Coupling" Watch "Loose Coupling" New topic
Author

Loose Coupling

Mike Thomson
Ranch Hand

Joined: Nov 07, 2007
Posts: 115


Can you please explain the above statement?


Somewhere I am missing to understand the above statement through coding. Please advice on it.
Steve Luke
Bartender

Joined: Jan 28, 2003
Posts: 4181
    
  21

The idea is that Class A doesn't really need to know about Class B, it just needs to know how to use Class B, which is to say it needs an interface to call, and doesn't really care who is calling it.

So if Class B looks like this:

And Class A needs to doSomething(), like you said, one way Class A could work is to call on an instance of B:


But now A has to know about B, and what happens when I want to change how B works, or add a different class C and let A work with either.

To make it so A doesn't really have to know about B (and so could work with C or D later on) we create an interface that mimics the methods A needs:

This just defines a method that can be used on any class that implements SomethingI. I can then code A against this interface:

And if I make B implement the SomethingI interface I can use it in A:


So now A is using B, but doesn't really know it - and doesn't care. A just cares about SomthingI. Which means when class C comes along I can use that without modifying A:


Steve
Mike Thomson
Ranch Hand

Joined: Nov 07, 2007
Posts: 115
Great explanation. Thank you so much Steve Luke.

Can I mean to say that, I always try to use:
interface i = new B();

Instead of
B b = new B();

Code to interface instead of code to implementation. Am I right?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39436
    
  28
Originally posted by Mike Thomson:
Code to interface instead of code to implementation. Am I right?


"Code to the interface" is probably correct in 99% of cases.
"Don't code to the implementation" is probably correct in 99% of cases.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Loose Coupling