Are circular class dependencies bad from a coding

2019-01-04 13:37发布

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 ConnFactoryto 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?

7条回答
别忘想泡老子
2楼-- · 2019-01-04 14:24

This code only works if ConnFactory.getConnection() is static. A better solution would be to make getConnection() an instance method of ConnFactory. Then your DBInfo can take a ConnFactory 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 that DBInfo would interact with and that ConnFactory would implement. Then there is no circular reference -- both DBInfo and ConnFactory would depend on IConnFactory, which would depend on neither.

查看更多
登录 后发表回答