Can anyone explain what is content coupling, and how it happened in the following code:
public class Line
{
private Point start, end;
...
public Point getStart() { return start; }
public Point getEnd() { return end; }
}
public class Arch
{
private Line baseline;
...
void slant(int newY)
{
Point theEnd = baseline.getEnd();
theEnd.setLocation(theEnd.getX(),newY);
}
}
Thank you.
Content coupling occurs when you have one instance stored inside another instance, and you modify the inner instance from the outer instance in a way that isn't intended or transparent.
Here, you have a Line
instance that's stored inside your Arch
instance; and the Line
stores two Point
s. When you invoke slant()
on your Arch
, it picks up one of the Point
s from inside the Line
, and changes it. The underlying Point
thus gets its state changed.
If this Point
were stored elsewhere in your application, it might get rather a shock when it discovered the Point
had moved.
In general, Content Coupling is a design defect where one module depends on implementation details of another module, instead of depending purely on it's public interface. Most of the time it means one module reads/writes data that is supposed to be encapsulated within another module, bypassing it's contract.
It's the tightest (worst) kind of coupling because such modules:
In your example Arch
is content coupled to Line
because Arch
modifies internal data of Line
(Point
instances).
Now if Line
had to change the way it stores data, or add additional code to handle point updates, the Arch
class would have to be updated as well, because it bypasses the interface of Line
and uses the interface of Point
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With