简体   繁体   中英

Tight coupling example not making sense

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?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM