Are Interfaces just "Syntactic Sugar"? - php

I've been playing mostly with PHP and Python.
I've been reading about Interfaces in OO programming and can't see an advantage in using it.
Multiple objects can implement the same interface, but multiple inheritance doesn't provide this as well?
Why do I need to create an Interface "with no implementation" - mainly a "contract" - if I can just check if a method exists in an object in Python, that inherits from multiple classes?
Do Interfaces were created in another languages because they don't provide multiple inheritance? Or am I missing something more important here?

First, and foremost, try not to compare and contrast between Python and Java. They are different languages, with different semantics. Compare and contrast will only lead to confusing questions like this where you're trying to compare something Python doesn't use with something Java requires.
It's a lot like comparing the number 7 and the color green. They're both nouns. Beyond that, you're going to have trouble comparing the two.
Here's the bottom line.
Python does not need interfaces.
Java requires them.
Multiple objects can implement the same interface, but multiple inheritance doesn't provide this as well?
The two concepts have almost nothing to do with each other.
I can define a large number of classes which share a common interface. In Python, because of "duck typing", I don't have to carefully be sure they all have a common superclass.
An interface is a declaration of "intent" for disjoint class hierarchies. It provides a common specification (that can be checked by the compiler) that is not part of the simple class hierarchy. It allows multiple class hierarchies to implement some common features and be polymorphic with respect to those features.
In Python you can use multiple inheritance with our without interfaces. Multiple inheritance can include interface classes or not include interface classes.
Java doesn't even have multiple inheritance. Instead it uses a completely different technique called "mixins".
Why do I need to create an Interface "with no implementation" - mainly a "contract" - if I can just check if a method exists in an object in Python, that inherits from multiple classes?
If you create an interface in Python, it can be a kind of formal contract. A claim that all subclasses will absolutely do what the interface claims.
Of course, a numbskull is perfectly free to lie. They can inherit from an interface and mis-implement everything. Nothing prevents bad behavior from sociopaths.
You create an interface in Java to allow multiple classes of objects to have a common behavior. Since you don't tell the compiler much in Python, the concept doesn't even apply.
Do Interfaces were created in another languages because they don't provide multiple inheritance?
Since the concepts aren't related, it's hard to answer this.
In Java, they do use "mixin" instead of multiple inheritance. The "interface" allows some mixing-in of additional functionality. That's one use for an interface.
Another use of an Interface to separate "is" from "does". The class hierarchy defines what an objects IS. The interface hierarchy defines what a class DOES.
In most cases, IS and DOES are isomorphic, so there's no distinction.
In some cases, what an object IS and what an object DOES are different.

The usefulness of an interface is directly connected to the usefulness of static typing. If you're working in a dynamically-typed language like PHP or Python, interfaces truly don't add significantly to the expressiveness of the language. That is, any program that can be described as using interfaces can be expressed without significant difference without using interfaces.
As a result, Python has a fairly nebulous concept of a "protocol" (an implementation conforming to a certain pattern, like the iteration protocol) which amounts to essentially the same thing, but without the other benefits of compile-time checking its value is limited.
In a statically-typed language, on the other hand, an interface is essential to allow implementation to be decoupled from implementation. In a static language, the types of all expressions must be resolved at compile time, so normally bindings to implementation must be made at that time, limiting run-time flexibility. An interface defines how to access functionality without defining a specific implementation, which allows a static language to prove that expressions are correct without having access to the implementation.
Without interfaces (or an equivalent formulation like C++'s pure virtual functions), the expressiveness of a statically-typed language would be severely hampered. In fact, many implementations exist (Win32 and COM come immediately to mind) to essentially reproduce much of the functionality of interfaces and virtual dispatch in C by storing function pointers in structures (and thus re-implementing C++'s virtual functions and vtable invocation by hand). In this case there is a big difference in expressiveness, since many changes are required in the program to express the same concepts.
Interfaces are just one example of type polymorphism, and a fairly limited one at that. In languages that support parametric polymorphism (aka generics) you can accomplish much more. (For example, C#'s LINQ would not be possible without generic interfaces.) For a much more powerful form of the same kind of thing, look into Haskell's typeclasses.

Even in duck-typed languages like Python, an interface can be a clearer statement of your intent. If you have a number of implementations, and they share a set of methods, an interface can be a good way to document the external behavior of those methods, give the concept a name, and make the concept concrete.
Without the explicit interface, there's an important concept in your system that has no physical representation. This doesn't mean you have to use interfaces, but interfaces provide that concreteness.

In dynamically typed languages, like PHP and Python, interfaces are only of limited use. You can already attempt to call methods on any object whenever, and you get a run-time error if it doesn't exist.
It's in statically typed languages, like Java and .NET, that interfaces become important, because methods and their arguments are checked at compile-time.
Now, for interfaces:
Java has Lists in addition to arrays. As a general rule, arrays are for primitives (the number types mainly), while Lists are for objects.
I can have a List<String>, which is a list of strings. I know I can add strings to it, and get strings back from it.
I don't know which implementation it is. It could be an ArrayList (list backed by an array), a LinkedList (list backed by a doubly linked list), a CopyOnWriteArrayList (thread-safe version of ArrayList), etc...
Thanks to polymorphism and interfaces, I don't need to know which type of List it is to do List operations on it.

Because you want to program against an interface and not a concrete implementation (GoF 1995:18)

Because sometimes you don't want to provide an implementation.
Java Interface
Java class

Yes. As for PHP, interfaces are just a means to overcome the lack of multiple inheritance. There are minor semantic differences useful for IDEs, and fewer conflicts caused by interfaces clearly aid newbie programmers. But as said before, it's not strictly necessary in dynamic languages.
http://c2.com/cgi/wiki?MultipleInheritance

Please read Twisted Framework article about power of Zope Interfaces in python.

It's generally implemented to replace multiple inheritance (C#).
I think some languages/programmers use them as a way of enforcing requirements for object structure as well.

Related

Differences between methods in PHP and Ruby

I'm just beginning to learn PHP. Sorry, if it's a newbie question but I'm wondering how methods work. For example, if I wanted to remove white spaces at the beginning of a string. In Ruby, I would call something like:
string.strip!
But in PHP, I would have to do something like:
trim(string);
Obviously, the Ruby version is more elegant(in terms of object-oriented design), but I'm wondering how it works for PHP and other languages such Java. Is there a name for designing functions/methods this way(in PHP)? And where are those methods defined and why can they be accessed anywhere? Thanks a lot in advance!
There are two different paradigms here: object-oriented programming (OOP) and procedural programming.
In OOP, functions are defined in the context of data, encapsulated by classes; such functions are usually called methods. When a method is called on an object (e.g. an instance of a class), it inherently has access to the state of that object. So, in your example, strip already knows what string it's being called on, and so doesn't require any additional arguments. Whenever your function naturally operates on a particular object or set of data (e.g. as strip acts on a string), it is sensible to define it as an instance method in this way.
In procedural programming, functions are defined independently data structures (classes), and must be explicitly passed the data they are to work with. Sometimes this approach is in fact more natural; for example, a print function that prints some input to stdout, or similar, isn't naturally associated with any particular object or data.
Most modern languages have OO features built into them, as it's a very versatile and powerful programming paradigm. Languages like Java and C# encourage all code to be written in an object-oriented style. In these languages, even the basic data-types like strings and floating points are in fact objects and have their own methods and state. This is particularly true in C#, where all types inherit ultimately from System.Object (even int and double) and inherit all the common methods defined thereby. This is called a unified type hierarchy.
PHP, on the other hand, has a curious mixture of OOP and procedural features; it started life as a procedural language, and OOP was only introduced in version 3 (and only in a very rudimentary sense). While, as of PHP5, it has relatively good OOP support, most of its standard library is still implemented procedurally as loose collections of functions that expect to have the relevant state/data passed to them as arguments. OOP libraries are becoming more common, however (e.g. with mysqli).
You're looking at, essentially, the different between instance methods and class/static methods. Instance methods are called on a specific instance of a class, and they have access to the internal state of that instance. Class/static methods are not, and do not.
I'm not sure what you're looking for in asking "how it works for PHP and ... Java." With regard to instance vs non-instance methods, Ruby, PHP, and Java all work roughly the same.

PHP4 and UML: does it make sense to design an object diagram?

I am documenting a PHP4 system I'm building for a client. The system will be written following an object-oriented logic, using the MVC pattern. I have already sketched up a class diagram; however, I am now wondering if it makes sense to create object diagrams for such a system, since it follows the OOP model rather loosely.
The closest thing to object-oriented behavior in this system will probably be a handful of methods changing their behavior based on how they're being called, although this can't exactly be called instancing straight-up classes; would an object diagram capture anything useful from this scenario, or am I better off just skipping them altogether? Thanks in advance.
In my experience, UML Class diagrams are best used in an isolated context -- to describe a section of the system.
So my answer is that if you are describing a piece of your system in a document, and a UML class diagram would help a reader understand the relevant section of the system then you should do a diagram for that section and include it.
Doing one class diagram for the entire system is rarely, if ever, useful. And including various class diagrams without context is also rarely useful.
Be strategic in your use of UML; it's a communication tool, not a documentation tool. (Sort of like writing. Words on paper means nothing unless used and organized thoughtfully)
I think the flexibility of your situation conflicts with expectations of UML.
I would suggest abstracting the implementation level from your diagram (and lie) and represent the functionality of those methods as independent methods performing their own work.

Why is PHP considered Object Oriented?

I have been reading around the definition of OOP and couldn't get why PHP is considered object oriented.
Can this have anything to do that the "basic level" of PHP isn't and more advanced features are?
OO features were added to PHP in stages through versions 3-5, after much of the standard library had already been created and the language was already established. Background
For this reason the standard library is not object-oriented and so everyday PHP scripts need not use any OO-style features at all. Although PHP by now has most of the standard features of an object-oriented language, many authors don't use them.
Library functions added to the language later continued to use functional style for consistency, though many extension modules do use objects.
Almost any language that allows you to create and instantiate classes can be considered object oriented.
PHP has these capabilities, but doesn't really stretch them. You can use OOP to help your code, but it isn't required. Java and C# barely allow you to write non-OO code, as everything must be in a class.
Can this have anything to do that the "basic level" of PHP isn´t and more advanced features are?
You could say that about just about any OO language. The general definition of OO code is where you create classes and instantiate them in your code, calling methods on them from other classes. Nothing stops you from using only static methods or one super class with a 'run' method that only calls other methods inside the class, both of which would definitely NOT be object oriented. As far as I know, there aren't any languages that say "You must create classes and instantiate them or you will be banished!" (I haven't looked into Smalltalk though).
Beginners often learn the basics while putting all their code in just one method that gets called at the stat of the program. Once they get to more 'advanced' features like methods and classes, they are offered other options.
There is already a sufficient (and accepted) answer here, but I thought I'd throw another log on the fire for clarity's sake.
The "class" keyword (and the enforcement of its ubiquity, as in Java) does not Object-Oriented Programming make. As CrazyJungleDrummer pointed out, it is perfectly feasible (and all too common) to write entirely procedural code in something like Java; the fact that the code lies between curly braces in a class called HelloWorld doesn't change that fact. And just hiding a bunch of functions in a class and calling them static methods isn't OOP either -- it's namespacing.
Think of a proper object as a struct (or "custom type", depending on your previous language exposure) that knows what to do. Objects are data that you don't (or shouldn't) act upon directly; you ask them to do things to themselves, and you ask them to tell you about themselves. You create entities and pass messages. OOP is about treating your data like it's all grown up and can handle itself. It's not about where the main line of code lives, but how data are treated.
Oh, and one more thing -- even in a language that is more obviously canted toward OOP, real OOP is not always the right approach. It's all about the data.
You can write classes with PHP, but most of the core features are not object-oriented.
It's been a long time since this question but I came upon this article and wanted to shre the author's point of view.
PHP is not object oriented!
This answer is inspired by this Man and his answer.
Object-Oriented technology is often described in
terms of encapsulation, polymorphism, and inheritance. But
these are only identity.
If object-oriented technology is to be successfully
it must emphasis on the object.
When we say Object-oriented or Object-orientation it can refer to several things:
Object-oriented analysis and design[OOAD]
Object-oriented design[OAD]
Object-oriented database
Object-oriented modeling
Object-oriented operating system
Object-oriented programming[OOP]-->topic of concern
Object-oriented software engineering
Object-oriented user interface
What Pure Object Oriented Programming Language[OOP] is?
Alan Kays["Considered by some to be the father of object-oriented programming"] [Defination]5 link by Gordon:
EverythingIsAnObject.
Objects communicate by sending and receiving messages (in terms of objects).
Objects have their own memory (in terms of objects).
Every object is an instance of a class (which must be an object).
The class holds the shared behavior for its instances (in the form of objects in a program list)
Now clearly it can be seen Java,C++ and PHP violates rule 1?Why bcoz int, float etc. (there are a total of eight primitive types). so it cannot be Object oriented in strict sense but some folk's considered it as OOP.
The general approach of OOP is to view a software system as a collection of interacting entities called "objects" each of which is defined by an identity, a state described in terms of member variables, and a behavior described in terms of methods that can be invoked
What OOP is not?
Object-Oriented technology is often described in
terms of encapsulation, polymorphism, and inheritance. But
these are only identity.
An Object Oriented system, language, or environment should include at least Encapsulation, Polymorphism, and Inheritance.
Polymorphism and Inheritance are certainly patterns that facilitate
OO programming, but not only bound to it
The object-oriented paradigm isn't completely the domain of
high-level programming languages -->may topic of debate but i came
across this OOP in Assembly
Uncle Bob aka Bob Martin in his lecture shows How C implements Encapsulation,Inheritance,and Polymorphism LINK
OO is based on modeling real-world objects // For Marketing purpose
Difference Between OOP and Functional?
This may be not be perfect answer but i gave a try,Thnks to knowledge of valley.
Note:
Images are randomly found on google

What is the point of interfaces in a weakly-typed language like PHP?

I've never been able to figure this out. If your language doesn't type-check, what benefits do interfaces provide you?
Interfaces cause your program to fail earlier and more predictably when a subclass "forgets" to implement some abstract method in its parent class.
In PHP's traditional OOP, you had to rely on something like the following to issue a run-time error:
class Base_interface {
function implement_me() { assert(false); }
}
class Child extends Base_interface {
}
With an interface, you get immediate feedback when one of your interface's subclasses doesn't implement such a method, at the time the subclass is declared rather than later during its use.
Taken from this link (sums it up nicely):
Interfaces allow you to define/create
a common structure for your classes –
to set a standard for objects.
Interfaces solves the problem of
single inheritance – they allow you
to inject ‘qualities’ from multiple
sources.
Interfaces provide a flexible
base/root structure that you don’t
get with classes.
Interfaces are great when you have
multiple coders working on a project
; you can set up a loose structure
for programmers to follow and let
them worry about the details.
I personally find interfacing a neat solution when building a DataAccess layer which has to support multiple DBMS's. Each DBMS implementation must implement the global DataAccess-interface with functions like Query, FetchAssoc, FetchRow, NumRows, TransactionStart, TransactionCommit, TransactionRollback etc. So when you're expanding your data-acccess posibilities you are forced to use a generic defined functionschema so you're application won't break at some point because you figured the function Query should now be named execQuery.
Interfacing helps you develop in the bigger picture :)
Types serve three distinct functions:
design
documentation
actual type checking
The first two don't require any form of type checking at all. So, even if PHP did no checking of interfaces, they would still be useful just for those two reasons.
I, for example, always think about my interfaces when I'm doing Ruby, despite the fact that Ruby doesn't have interfaces. And I often wish I could have some way of recording those design decisions in the source code.
On the other hand, I have seen plenty of Java code that used interfaces, but clearly the author never thought about them. In fact, in one case, one could see from the indentation, whitespace and some leftover comments in the interface that the author had actually just copied and pasted the class definition and deleted all method bodies.
Now to the third point: PHP actually does type check interfaces. Just because it type checks them at runtime doesn't mean it doesn't type check them at all.
And, in fact, it doesn't even check them at runtime, it checks them at load time, which happens before runtime. And isn't "type checking doesn't happen at runtime but before that" pretty much the very definition of static type checking?
You get errors if you haven't added the required methods with the exact same signature.
Interfaces often used with unit-testing (test-driven design).
it also offers you more stable code.
the interfaces are also used to support iterators (eg. support for foreach on objects) and comparators.
It may be weakly typed, but there is type hinting for methods: function myFunc(MyInterface $interface)
Also, interfaces do help with testing and decoupling code.
Type hinting in function/method signatures allows you to have much more control about the way a class interfaces with it's environment.
If you'd just hope that a user of your class will only use the correct objects as method parameters, you'll probably run into trouble. To prevent this, you'd have to implement complicated checks and filters that would just bloat your code and definitely have would lower your codes performance.
Type hinting gives you a tool to ensure compatibility without any bloated, hand written checks. It also allows your classes to tell the world what they can do and where they'll fit in.
Especially in complex frameworks like the Zend Framework, interfaces make your live much easier because they tell you what to expect from a class and because you know what methods to implement to be compatible to something.
In my opinion, there's no point, no need and no sense. Things like interfaces, visibility modifiers or type hints are designed to enforce program "correctness" (in some sense) without actually running it. Since this is not possible in a dynamic language like php, these constructs are essentially useless. The only reason why they were added to php is make it look more like java, thus making the language more attractive for the "enterprise" market.
Forgot to add: uncommented downvoting sucks. ;//

Is there any point for interfaces in dynamic languages?

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?
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.
Interfaces actually add some degree of dynamic lang-like flexibility to static languages that have them, like Java. They offer a way to query an object for which contracts it implements at runtime.
That concept ports well into dynamic languages. Depending on your definition of the word "dynamic", of course, that even includes Objective-C, which makes use of Protocols pretty extensively in Cocoa.
In Ruby you can ask whether an object responds to a given method name. But that's a pretty weak guarantee that it's going to do what you want, especially given how few words get used over and over, that the full method signature isn't taken into account, etc.
In Ruby I might ask
object.respond_to? :sync
So, yeah, it has a method named "sync", whatever that means.
In Objective-C I might ask something similar, i.e. "does this look/walk/quack like something that synchronizes?":
[myObject respondsToSelector:#selector(sync)]
Even better, at the cost of some verbosity, I can ask something more specific, i.e. "does this look/walk/quack like something that synchronizes to MobileMe?":
[myObject respondsToSelector:#selector(sync:withMobileMeAccount:)]
That's duck typing down to the species level.
But to really ask an object whether it is promising to implement synchronization to MobileMe...
[receiver conformsToProtocol:#protocol(MobileMeSynchronization)]
Of course, you could implement protocols by just checking for the presence of a series of selectors that you consider the definition of a protocol/duck, and if they are specific enough. At which point the protocol is just an abbreviation for a big hunk of ugly responds_to? queries, and some very useful syntactic sugar for the compiler/IDE to use.
Interfaces/protocols are another dimension of object metadata that can be used to implement dynamic behavior in the handling of those objects. In Java the compiler just happens to demand that sort of thing for normal method invocation. But even dynamic languages like Ruby, Python, Perl, etc. implement a notion of type that goes beyond just "what methods an object responds to". Hence the class keyword. Javascript is the only really commonly used language without that concept. If you've got classes, then interfaces make sense, too.
It's admittedly more useful for more complicated libraries or class hierarchies than in most application code, but I think the concept is useful in any language.
Also, somebody else mentioned mixins. Ruby mixins are a way to share code -- e.g., they relate to the implementation of a class. Interfaces/protocols are about the interface of a class or object. They can actually complement each other. You might have an interface which specifies a behavior, and one or more mixins which help an object to implement that behavior.
Of course, I can't think of any languages which really have both as distinct first-class language features. In those with mixins, including the mixin usually implies the interface it implements.
If you do not have hight security constraints (so nobody will access you data a way you don't want to) and you have a good documentation or well trained coders (so they don't need the interpreter / compiler to tell them what to do), then no, it's useless.
For most medium size projects, duck typing is all you need.
I was under the impression that Python doesn't have interfaces. As far as I'm aware in Python you can't enforce a method to be implemented at compilation time precisely because it is a dynamic language.
There are interface libraries for Python but I haven't used any of them.
Python also has Mixins so you could have create an Interface class by defining a Mixin an having pass for every method implementation but that's not really giving you much value.
I think use of interfaces is determined more by how many people will be using your library. If it's just you, or a small team then documentation and convention will be fine and requiring interfaces will be an impediment. If it's a public library then interfaces are much more useful because they constrain people to provide the right methods rather than just hint. So interfaces are definitely a valuable feature for writing public libraries and I suppose that lack (or at least de-emphasis) is one of the many reasons why dynamic languages are used more for apps and strongly-typed languages are used for big libraries.
Rene, please read my answer to "Best Practices for Architecting Large Systems in a Dynamic Language" question here on StackOverflow. I discuss some benefits of giving away the freedom of dynamic languages to save development effort and to ease introducing new programmers to the project. Interfaces, when used properly, greatly contribute to writing reliable software.
In a language like PHP where a method call that doesn't exist results in a fatal error and takes the whole application down, then yes interfaces make sense.
In a language like Python where you can catch and handle invalid method calls, it doesn't.
Python 3000 will have Abstract Base Classes. Well worth a read.
One use of the Java "interface" is to allow strongly-typed mixins in Java. You mix the proper superclass, plus any additional methods implemented to support the interface.
Python has multiple inheritance, so it doesn't really need the interface contrivance to allow methods from multiple superclasses.
I, however, like some of the benefits of strong typing -- primarily, I'm a fan of early error detection. I try to use an "interface-like" abstract superclass definition.
class InterfaceLikeThing( object ):
def __init__( self, arg ):
self.attr= None
self.otherAttr= arg
def aMethod( self ):
raise NotImplementedError
def anotherMethod( self ):
return NotImplemented
This formalizes the interface -- in a way. It doesn't provide absolute evidence for a subclass matching the expectations. However, if a subclass fails to implement a required method, my unit tests will fail with an obvious NotImplemented return value or NotImplementedError exception.
Well, first of all, it's right that Ruby does not have Interface as is, but they have mixin, wich takes somehow the best of both interfaces and abstract classes from other languages.
The main goal of interface is to ensure that your object SHALL implement ALL the methods present in the interface itself.
Of course, interface are never mandatory, even in Java you could imagine to work only with classes and using reflection to call methods when you don't know wich kind of object you're manipulating, but it is error prone and should be discouraged in many ways.
Well, it would certainly be easier to check if a given object supported an entire interface, instead of just not crashing when you call the one or two methods you use in the initial method, for instance to add an object to an internal list.
Duck typing has some of the benefits of interfaces, that is, easy of use everywhere, but the detection mechanism is still missing.
It's like saying you don't need explicit types in a dynamically-typed language. Why don't you make everything a "var" and document their types elsewhere?
It's a restriction imposed on a programmer, by a programmer. It makes it harder for you to shoot yourself in the foot; gives you less room for error.
as a PHP programmer, the way I see it, an Interface is basically used as a contract. It lets you say that everything which uses this interface MUST implement a given set of functions.
I dunno if that's all that useful, but I found it a bit of a stumbling block when trying to understand what Interfaces were all about.
If you felt you had to, you could implement a kind of interface with a function that compares an object's methods/attributes to a given signature. Here's a very basic example:
file_interface = ('read', 'readline', 'seek')
class InterfaceException(Exception): pass
def implements_interface(obj, interface):
d = dir(obj)
for item in interface:
if item not in d: raise InterfaceException("%s not implemented." % item)
return True
>>> import StringIO
>>> s = StringIO.StringIO()
>>> implements_interface(s, file_interface)
True
>>>
>>> fp = open('/tmp/123456.temp', 'a')
>>> implements_interface(fp, file_interface)
True
>>> fp.close()
>>>
>>> d = {}
>>> implements_interface(d, file_interface)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in implements_interface
__main__.InterfaceException: read not implemented.
Of course, that doesn't guarantee very much.
In addition to the other answers I just want to point out that Javascript has an instanceof keyword that will return true if the given instance is anywhere in a given object's prototype chain.
This means that if you use your "interface object" in the prototype chain for your "implementation objects" (both are just plain objects to JS) then you can use instanceof to determine if it "implements" it. This does not help the enforcement aspect, but it does help in the polymorphism aspect - which is one common use for interfaces.
MDN instanceof Reference
Stop trying to write Java in a dynamic language.

Categories