问题描述
我在一个Java程序员团队中工作.我的一位同事不时建议我做类似仅添加类型字段"(通常是字符串类型")之类的事情.否则代码将被装载"if (foo instanceof Foo){...} else if( foo instanceof Bar){...}
".
I work on a team of Java programmers. One of my co-workers suggests from time-to-time that I do something like "just add a type field" (usu. "String type"). Or code will be committed laden with "if (foo instanceof Foo){...} else if( foo instanceof Bar){...}
".
尽管有乔什·布洛赫(Josh Bloch)的告诫,标记类是对适当的类层次结构的完全模仿",但是我对这种事情的单向反应是什么?然后我如何更认真地阐述这个概念呢?
Josh Bloch's admonition that "tagged classes are a wan imitation of a proper class hierarchy" notwithstanding, what is my one-line response to this sort of thing? And then how do I elaborate the concept more seriously?
对我来说很明显-上下文是Java-正在考虑的对象类型恰好在我们集体面前-IOW:类",枚举"或接口"等之后的单词.
It's clear to me that - the context being Java - the type of Object under consideration is right in front of our collective faces - IOW: The word right after the "class", "enum" or "interface", etc.
但是,除了难以演示或量化(当场)它使您的代码更加复杂"之外,我怎么说使用(或多或少)强类型语言进行鸭式输入是一种愚蠢的想法暗示了更深层的设计病理?
But aside from the difficult-to-demonstrate or quantify (on the spot) "it makes your code more complicated", how do I say that "duck-typing in a (more or less) strongly-typed language is a stupid idea that suggests a much deeper design pathology?
推荐答案
当您说鸭子在强类型语言中键入"时,您实际上的意思是在静态类型语言中模仿(子类型)多态".
When you say "duck typing in strongly-typed languages" you actually mean "imitating (subtype) polymorphism in statically-typed languages".
当您拥有不包含任何行为的数据对象(DTO)时,还不错.如果确实有成熟的OO模型(如果确实如此,请问自己),那么应该在适当的地方使用该语言提供的多态性.
It's not that bad when you have data objects (DTOs) that don't contain any behaviour. When you do have a full-blown OO model (ask yourself if this is really the case) then you should use the polymorphism offered by the language where appropriate.
这篇关于我该如何反对像Java这样的强类型语言中的Duck-typing?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!