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 supports interfaces. Ruby and Python don't have them. So you can clearly live happily without them.
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?
Advantages of dynamically-typed languages:More succinct/less verbose. The absence of a separate compilation step (which is much more common) means that you don't have to wait for the compiler to finish before you can test changes that you've made to your code.
Python does not have interfaces, but the same functionality can be achieved with the help of abstract base classes and multiple inheritance. The reason for not having interfaces is that Python does not use static typing, so there's no compile-time type checking.
Dynamically typed languages must make all of their checks at runtime because the type might change during the course of the execution. Static typed languages resolve all types during compile time so the cost is consumed up front, one time. This is the main reason why dynamic typed languages are typically slower.
No. Dynamic languages are not slower than static languages. In fact, it is impossible for any language, dynamic or not, to be slower than another language (or faster, for that matter), simply because a language is just a bunch of abstract mathematical rules.
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.
Yes, there is a point
If you don't explicitly use interfaces your code still uses the object as though it implemented certain methods it's just unclear what the unspoken interface is.
If you define a function to accept an interface (in PHP say) then it'll fail earlier, and the problem will be with the caller not with the method doing the work. Generally failing earlier is a good rule of thumb to follow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With