从编码风格的角度来看,循环类的依赖性不好吗? [英] Are circular class dependencies bad from a coding style point of view?

查看:79
本文介绍了从编码风格的角度来看,循环类的依赖性不好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



示例:



在数据库应用程序中,我们有两个类,一个封装有关单个数据库的信息( DBInfo )和一个可以创建数据库连接的类。 ( ConnFactory



DBInfo 有一个 getConnection 方法,使用 ConnFactory 创建连接。但是 ConnFactory 本身需要一个 DBInfo 对象。



像这样:(为了可读性而忽略任何编码风格)

  class DBInfo {
String name;
String connectionUrl;

连接getConnection(){
return ConnFactory.getConnection(this);
}
}


class ConnFactory {
连接getConnection(DBInfo toWhat){
返回新连接(toWhat.connectionUrl);
}
}

我的同事认为这是不好的做法如果只有一个依赖方向,而不是这样的循环方式,那将会更好。



这是不好的做法,反模式还是代码气味?有没有任何缺点?

解决方案

一般来说,我会将循环依赖关联为代码气味。请注意,术语代码气味主要表示这是一段需要特别注意的代码,可能会从重新设计中受益。



在大多数情况下我会强烈地考虑一个不需要循环依赖的设计,但在极少数情况下可能还可能。



在您的示例中,ConnFactory似乎是多余的,但是是因为你的例子被修剪了。然而,在我看来,如果连接创建逻辑被移动到DBInfo类,它将会更好。当您已经有一个包含有关数据库的数据库的类时,它似乎只是自己负责创建与该数据库的连接。


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?

解决方案

In general, I would call circular dependencies a Code Smell. Note that the term 'Code Smell' mainly indicates that 'here is a piece of code that requires special attention, and is likely to benefit from redesign.'

In most cases I would strongly consider a design where a circular dependency is not necessary, but in rare cases it may be okay.

In your example, the ConnFactory seems redundant, but that may be because your example has been trimmed down. It seems to me, however, that the Connection creation logic would be better if it was moved to the DBInfo class. When you already have a class that contains data about a database, it seems only natural to make it responsible for creating a connection to that database.

这篇关于从编码风格的角度来看,循环类的依赖性不好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆