我刚才读了维基百科的文章关于duck typing,我觉得我想念的界面概念,我在Java中使用到的重要一点:鸭打字和(JAVA)的接口概念
"When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck."
class Duck:
def quack(self):
print("Quaaaaaack!")
def feathers(self):
print("The duck has white and gray feathers.")
def swim(self):
print("Swim seamlessly in the water")
class Person:
def quack(self):
print("The person imitates a duck.")
def feathers(self):
print("The person takes a feather from the ground and shows it.")
def name(self):
print("John Smith")
def in_the_forest(duck):
duck.quack()
duck.feathers()
def game():
donald = Duck()
john = Person()
in_the_forest(donald)
in_the_forest(john)
game()
如果什么,在in_the_forest
,我写:
- 做它
quack
如鱼得水?是 - 它有一只鸭子
feathers
?是的 - 太棒了,这是我们的鸭子!
以后,因为我知道这是一只鸭子,我想要它swim
? john
会下沉!
我不希望我的应用程序在其进程中间崩溃(随机),只是因为John伪造成鸭子,但我想检查对象的每个属性都不是明智的做法当我收到它...?
+1:提出的问题 – msw
总之,你不用担心。您编写的测试涵盖了尽可能多的代码路径和角落案例,但是100%的安全性是不可能的。并且请注意,Java或其他大多数静态类型系统无法保证100%的安全性) – delnan
+1:关于重要主题的一个非常好的问题,重中之重。对不起,我只能给它1 upvote。 – Dave