1

Generally speaking, should one strive to align a class's dependencies with its imports?

For example, should one generally avoid doing something like this:

Bar.java:

import com.somepackage.Foo;
import com.somepackage.Baz;

public Bar(Foo foo) {...}

public void doSomething(Baz baz) {...}

Baz.java:

import com.somepackage.Bar;

public Baz(Bar bar) {...}

//etc...

Basically, Bar.java imports/uses/works with something that has it as a dependency, which seems odd. Although, I'm not sure if classes using their dependents necessarily constitutes some sort of smell (i.e., compile-time dependencies do not line up with run-time dependencies, hinting that some refactoring should probably be done...)

Roman C
  • 49,761
  • 33
  • 66
  • 176
ManRow
  • 1,563
  • 4
  • 21
  • 40
  • Keep in mind that imports don't have much to do conceptually with dependencies. They serve merely for name resolution. The presence of an import **does not** create a dependency to the named class. – Marko Topolnik Nov 17 '12 at 12:10
  • sure, I'm just wondering if this bad design-wise – ManRow Nov 17 '12 at 12:12

2 Answers2

1

I think this is a design smell. Can you extract a third class that resolves the cyclic dependency? Should one direction of the dependency be decoupled with an interface?

Without details of how the classes depend on each other it will be hard to be more specific.

WW.
  • 23,793
  • 13
  • 94
  • 121
-1

This is an example for cyclic dependency, Java allows it.

See Circular dependency in java classes

Design wise I feel it is ok to have this sort of dependency within a package.

Community
  • 1
  • 1
Subin Sebastian
  • 10,870
  • 3
  • 37
  • 42