在不同的命名空间中具有相同名称的类型是否可以接受?

发布于 2024-09-12 10:10:49 字数 105 浏览 0 评论 0原文

我在同一个代码库中看到 7 种类型都称为错误。这是可以接受的吗?

我的直觉告诉我,在不同的域上下文中具有相同名称的类型是可以的,但是在处理“母解决方案”时,它会越来越容易产生歧义。

I see 7 types all called Error within the same codebase. Is this acceptable?

My instinct says that having types with the same name in different domain contexts is OK, but it makes ambiguities increasingly likely when dealing with the "mother solution".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

韬韬不绝 2024-09-19 10:10:49

如果它们位于不同的命名空间中,那么这是可以的 - 这就是命名空间的用途。如果命名空间处理系统的不同部分,为什么要将它们耦合在一起以使用共享错误类型。如果命名空间由于其他原因而耦合,那么您可能会认为它们可以共享相同的错误类型来共享代码。

If they are in different namespaces then this is OK - this is what namespaces are for. If the namespaces deal with different parts of the system why should they be coupled together to use shared Error types. If the namespaces are coupled for other reasons then you might be able to argue that they could share the same Error type to share code.

童话 2024-09-19 10:10:49

就编译器而言,相同命名的类型是完全合法的。然而,尽管编译器很乐意区分引用和 using 语句明确的类型,但这并不意味着它对于阅读代码的程序员来说是明确的。

Error 听起来可能相当于 Exception 类,它是 CLR 异常类型层次结构的基础;这似乎是描述错误的一个很好的模型。也许您可以将错误类之间的常见行为提取到名为 Error 的单个基类中,然后从中继承以生成更简洁或特定于项目的子类。

Identically named types are perfectly legitimate as far as the compiler is concerned. However, although the compiler will happily distinguish between the types provided the references and using statements are unambiguous, this does not mean that it is unambiguous for a programmer reading the code.

Error sounds like it could be an equivalent of the Exception class which is the base of the CLR exception type hierarchy; this seems like a good model for describing errors. Perhaps you could pull out common behaviour between your error classes into a single base class called Error, and then inherit from this to produce more concise or project-specific subclasses.

油焖大侠 2024-09-19 10:10:49

命名空间的想法就是允许这样做,并且在许多情况下,这是可以的。另一方面,它使某些事情变得更加困难

  • 对特定类型的所有地点的全局搜索可能会得到太多的结果

  • < p>将这些类型之一移动到更顶级的组件以实现更广泛的重用可能会更困难。

无论如何,恕我直言,这不是一个全有或全无的决定。每次为另一个名称空间中已有的类型选择名称时,如果可能没有更好的名称,则应该重新考虑一两秒钟,从而避免这种情况。

The idea of namespaces is to allow this, and in many situations, it is ok. On the other hand, it makes some things harder

  • global search for all places of a specific type may suffer from getting too many results

  • moving one of those types to a more top-level component for wider re-use may be harder.

At all, IMHO it is not a all-or-nothing decision. Every time you choose a name for a type already there in another namespace, you should reconsider for a second or two if there may be not a better name, avoiding this.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文