Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is content coupling?

Tags:

java

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.

like image 859
Linda Avatar asked Nov 28 '14 11:11

Linda


2 Answers

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 Points. When you invoke slant() on your Arch, it picks up one of the Points 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.

like image 164
chiastic-security Avatar answered Oct 17 '22 22:10

chiastic-security


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:

  • present poor abstractions
  • are difficult to understand
  • can't be changed independently of one another

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.

like image 24
astreltsov Avatar answered Oct 17 '22 23:10

astreltsov