4

Is it bad practice to have a circular dependency between classes that are in the same Java package?

If not, I would like a reputable reference to a guideline somewhere that says so.

Danish Khan
  • 1,514
  • 3
  • 15
  • 22
  • Acceptable _how_? As in "will it compile"? Try it. – Sotirios Delimanolis Apr 28 '16 at 01:49
  • I meant good/bad practice. I did a little refactor to avoid this and I've been told by a team member that it should be ok to have a circular dependency as long as it's within the same package. – Danish Khan Apr 28 '16 at 01:51
  • 3
    Related: http://stackoverflow.com/questions/9173494/are-circular-dependencies-considered-bad-design?rq=1 http://stackoverflow.com/questions/1356304/are-circular-class-dependencies-bad-from-a-coding-style-point-of-view?lq=1 – Thilo Apr 28 '16 at 02:05

1 Answers1

12

In and of themselves, circular dependencies are not a problem. However, what they point to - tight coupling - generally can be a problem. Essentially, by tightly coupling two classes you're accepting that a change in one is likely to result in a change in the other. That can be an issue if the two classes have different responsibilities - effectively, by tightly coupling them you're saying that they share their responsibilities, and so violating the Single Responsibility Principle.

If you've got a circular dependency between two classes in the same package then there are some immediate questions to answer:

  • why not merge them into a single class?

  • why not make one an inner class of the other?

  • why not decouple them through judicious use of interfaces?

  • is there another class design which would make more sense?

The further apart your tightly-coupled classes are the greater the urgency of those, and other, questions. Partly that's about how close the classes are in terms of packages - within the same package in the same artifact is less of a concern than between different packages in the same artifact. However, it's also true that if they classes are in different aritfacts (i.e. jars) but in the same package then they shouldn't be tightly coupled - because that could result in clients being unable to independently upgrade the library dependency versions.

For a 'reputable' reference on the subject you could do worse than Bob Martin's book "Agile Software Development".

sisyphus
  • 6,174
  • 1
  • 25
  • 35