Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Loose Coupling

 
Mike Thomson
Ranch Hand
Posts: 121
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 4181
21
IntelliJ IDE Java Python
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Mike Thomson
Ranch Hand
Posts: 121
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 48981
60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic