Are circular class dependencies bad from a coding style point of view?
Example:
In a database application we have two classes, one encapsulating information about a single database (DBInfo
) and one class which can create a database connection. (ConnFactory
)
DBInfo
has a getConnection
method which uses ConnFactory
to create a connection. But ConnFactory
itself needs a DBInfo
object to do so.
Like this: (Any coding styles disregarded for the sake of readability)
class DBInfo {
String name;
String connectionUrl;
Connection getConnection() {
return ConnFactory.getConnection(this);
}
}
class ConnFactory {
Connection getConnection(DBInfo toWhat) {
return new Connection(toWhat.connectionUrl);
}
}
My co-workers argue that this is bad practice and it would be better if there were only one direction of dependencies and no circular ones like here.
Is this bad practice, an anti-pattern or a code smell? Are there any drawbacks?
This code only works if
ConnFactory.getConnection()
is static. A better solution would be to makegetConnection()
an instance method ofConnFactory
. Then your DBInfo can take aConnFactory
as an argument (possibly in a constructor, if you have an overloaded constructor). However, I think the use of the static method for this case is more of a bad practice than the circular reference.If you were to go this route, though, I would also make an interface
IConnFactory
thatDBInfo
would interact with and thatConnFactory
would implement. Then there is no circular reference -- bothDBInfo
andConnFactory
would depend onIConnFactory
, which would depend on neither.