在基类中隐藏成员是否在代码中有难闻的气味? [英] Is hiding a member in the base class a bad smell in the code?
问题描述
对我来说,听起来更像是在基类中隐藏成员以破解某些东西而不是重构不良设计的异常...
To me, it sounds more like an exception to hide a member in the base class in order to hack something instead of refactoring a bad design...
也许我错了.但是...
Maybe I am wrong. But...
使用'new'关键字在基类中隐藏成员是一种代码味道吗?
Is it a code smell to hide a member in the base class with 'new' keyword?
推荐答案
这取决于意图.例如,如果目的是弄清具体的返回类型,那么它可能不是没有道理的.这里的经典示例是DbConnection
. SqlConnection
通过返回SqlCommand
而不是DbCommand
来重新声明CreateCommand
等,因为SqlCommand
具有许多特定于平台的功能,否则将很痛苦.不过,关键是DbConnection
方法仍然可以使用,并且这两种方法的目的和含义是相同的.
It depends on the intent. If the purpose is to clarify the concrete return type, for example, then it might not be unreasonable. The classic example here is DbConnection
. It is useful that SqlConnection
re-declares CreateCommand
etc, by returning SqlCommand
rather than DbCommand
, since SqlCommand
has many platform-specific features that would otherwise be a pain. A key point, here, though is that the DbConnection
method still works, and the purpose and meaning of the two methods is the same.
如果您执行此操作,并且方法做不同的事情,或返回不同的事情,那么有时可能会引起混乱.有时它仍然是有意义的; p如果他们做同样的事情,并且仅通过形式上声明对调用者有用的实现 有所不同,就可以了.
If you are doing this and the methods do something different, or return something different, then there are occasions it can cause confusion. And times it can still make sense ;p If they do the same thing, and only vary by formally stating something about the implementation that is useful to the caller, then fine.
这篇关于在基类中隐藏成员是否在代码中有难闻的气味?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!