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

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

问题描述

从编码风格的角度来看,循环类依赖是坏的吗?

Are circular class dependencies bad from a coding style point of view?

示例:

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

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 有一个 getConnection 方法,它使用 ConnFactory 来创建连接.但是ConnFactory 本身需要一个DBInfo 对象来实现.

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.

在您的示例中,ConnFactory 似乎是多余的,但这可能是因为您的示例已被删减.然而,在我看来,如果将 Connection 创建逻辑移到 DBInfo 类会更好.如果您已经有一个包含有关数据库的数据的类,那么让它负责创建与该数据库的连接似乎很自然.

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天全站免登陆