Interfaces: profit of using
Posted
by
Zapadlo
on Programmers
See other posts from Programmers
or by Zapadlo
Published on 2012-04-03T20:39:32Z
Indexed on
2012/04/03
23:40 UTC
Read the original article
Hit count: 150
First of all, my ubiquitous language is PHP, and I'm thinking about learning Java.
So let me split my question on two closely related parts.
Here goes the first part.
Say I have a domain-model class. It has some getters, setters, some query methods etc. And one day I want to have a possibility to compare them. So it looks like:
class MyEntity extends AbstractEntity
{
public function getId()
{
// get id property
}
public function setId($id)
{
// set id property
}
// plenty of other methods that set or retrieve data
public function compareTo(MyEntity $anotherEntity)
{
// some compare logic
}
}
If it would have been Java, I should have implemented a Comparable
interface. But why? Polymorphism? Readbility? Or something else? And if it was PHP -- should I create Comparable
interface for myself?
So here goes the second part.
My colleague told me that it is a rule of thumb in Java to create an interface for every behavioral aspect of the class. For example, if I wanted to present this object as a string, I should state this behaviour by something like implements Stringable
, where in case of PHP Stringable
would look like:
interface Stringable
{
public function __toString();
}
Is that really a rule of thumb? What benefits are gained with this approach? And does it worth it in PHP? And in Java?
© Programmers or respective owner