How is duck typing different from the old 'variant' type and/or interfaces?

后端 未结 10 1000
无人及你
无人及你 2021-01-30 03:32

I keep seeing the phrase \"duck typing\" bandied about, and even ran across a code example or two. I am way too lazy busy to do my own research, can someone tel

10条回答
  •  盖世英雄少女心
    2021-01-30 03:46

    In regards to your request for an example of something you'd need to use duck typing to accomplish, I don't think such a thing exists. I think of it like I think about whether to use recursion or whether to use iteration. Sometimes one just works better than the other.

    In my experience, duck typing makes code more readable and easier to grasp (both for the programmer and the reader). But I find that more traditional static typing eliminates a lot of needless typing errors. There's simply no way to objectively say one is better than another or even to say what situations one is more effective than the other.

    I say that if you're comfortable using static typing, then use it. But you should at least try duck typing out (and use it in a nontrivial project if possible).

    To answer you more directly:

    ...so again i'm just not getting it. Is it a fantastic time-saver, or the same old thing in a brand new sack?

    It's both. You're still attacking the same problems. You're just doing it a different way. Sometimes that's really all you need to do to save time (even if for no other reason to force yourself to think about doing something a different way).

    Is it a panacea that will save all of mankind from extinction? No. And anyone who tells you otherwise is a zealot.

提交回复
热议问题