Reputation: 119
public class TightlyCoupledClient{
public static void main(String[] args) {
TightlyCoupledServer server = new TightlyCoupledServer();
server.x=5; //should use a setter method
System.out.println("Value of x: " + server.x);
}
}
class TightlyCoupledServer {
public int x = 0;
}
In "SCJP exam for J2SE 5 Platform" in states that if both a and b use each other, they are tightly coupled. It the uses the above example. But TightlyCoupledServer dosent seem as though it uses TightlyCoupledClient. How have i got this wrong?
Upvotes: 0
Views: 96
Reputation: 132530
These class are mutually dependent, but in a rather subtle way.
Clearly, TightlyCoupledClient
depends directly on TightlyCoupledServer
. It's right there in the source code.
In what sense is TightlyCoupledServer
dependent on TightlyCoupledClient
? Well, the server class has a public field, and presumably it relies on its clients -- all of them, not just TightlyCoupledClient
-- to write to this field properly. Therefore, to verify the correctness of TightlyCoupledServer
one has to examine the code for everything in the system that could possibly write to this field.
Consider writing a unit test for TightlyCoupledServer
. We'd want to write something like:
assertEquals("x should be 5", 5, x);
For this assertion to be true, the code in TightlyCoupledClient
must be correct and must have been run prior to this assertion. And there's your dependency.
Upvotes: 0
Reputation: 726977
Mutual dependency is only one case of when coupling is considered tight. Another case of tight coupling is the so-called content coupling, which occurs when one module modifies or relies on the internal workings of another module. Knowledge of the class name is considered part of inner workings of the TightlyCoupledServer
module; so is the knowledge of its member variables.
Adding an interface and programming to it would decrease coupling. Injecting the code with an instance of TightlyCoupledServer
that implements an interface would further reduce coupling.
Upvotes: 1
Reputation: 1992
Tight coupling in simple words means, one class is directly dependent on other. So, if modifications happen in one, you will have to test functionality of both class for any behavior mismatch.
Here TightlyCoupledClient is directly dependent on TightlyCoupledServer. So, if you modify something like constructor for TightlyCoupledServer, you will have to test the changes appropriately for TightlyCoupledClient.
Upvotes: 0