动态语言中的接口有什么意义吗? [英] Is there any point for interfaces in dynamic languages?

查看:98
本文介绍了动态语言中的接口有什么意义吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在像Java这样的静态语言中你需要接口,因为
否则类型系统就不会让你做某些事情。
但是在像PHP和Python这样的动态语言中你只需要获得 duck-typing
优势。

In static languages like Java you need interfaces because otherwise the type system just won't let you do certain things. But in dynamic languages like PHP and Python you just take advantage of duck-typing.

PHP支持接口。
Ruby和Python没有它们。
所以你可以在没有他们的情况下幸福地生活。

PHP supports interfaces. Ruby and Python don't have them. So you can clearly live happily without them.

我一直在用PHP工作,而且从来没有真正用
来使用定义接口的能力。当我需要
类来实现某些通用接口时,那么
我只是在文档中描述它。

I've been mostly doing my work in PHP and have never really made use of the ability to define interfaces. When I need a set of classes to implement certain common interface, then I just describe it in documentation.

所以,你怎么看? ?如果不使用动态语言中的
接口,你不是最好的吗?

So, what do you think? Aren't you better off without using interfaces in dynamic languages at all?

推荐答案

我认为它更像是方便的水平。如果你有一个函数,它接受一个类文件对象并且只调用read()方法,那么强迫用户实现某种File接口是不方便的 - 甚至是限制。检查对象是否具有读取方法同样容易。

I think of it more as a level of convenience. If you have a function which takes a "file-like" object and only calls a read() method on it, then it's inconvenient - even limiting - to force the user to implement some sort of File interface. It's just as easy to check if the object has a read method.

但是如果您的函数需要大量方法,则更容易检查对象是否支持接口然后检查每种方法的支持。

But if your function expects a large set of methods, it's easier to check if the object supports an interface then to check for support of each individual method.

这篇关于动态语言中的接口有什么意义吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆