Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create interface for object or for action / behavior?

When come to create an interface, do u create it based on behavior, follow the -able standard, e.g.

interface Comparable
interface Enumerable
interface Listable
interface Talkable
interface Thinkable

Or based on object, e.g.

interface Comparator
interface Enumerator
interface List
interface Human

And why?

UPDATE

This question is not about the naming convention (-able suffix or I- prefix). This is about the design intention of the interface, and the impact of it, in terms of:-

  1. flexibility
  2. complexity / simplicity
  3. maintainability

For example, if I need to implement different features, by doing -able way, I can declare my class as

public class Man implements Talkable, Thinkable, Laughable
public class Woman implements Talkable, Thinkable, Laughable

On the other hand, if we create interface based on object, we can use it as

public class Man implements Human
public class Woman implements Human

And we can also use it for polymorphism purpose.

Human man = new Man();
like image 518
janetsmith Avatar asked Feb 28 '23 08:02

janetsmith


1 Answers

Interfaces are not about what a concrete class does. They are more about what the client needs, and what is substitutable in place of what the client needs. For example, instead of trying to extract an interface from a Man class, instead focus on one of the classes that use the Man class. What does it do? Perhaps it is a Conversation class that wants to make things talk to each other. If you gave it two Man classes, it could call talk() on them. But if you wanted it to be more flexible, you can abstract out the concept of what it does - makes things talk, and have it use a Talkable interface (for example). When you see a Talkable interface on this Conversation class, you shouldn't think "that is really a Man" but rather, "Where I see a Talkable, I can substitute anything that implements Talkable, whether it is a Man, Woman, Parrot, Robot, etc."

If I am unclear, there are good resources available on the subject. Check out Robert Martin's Dependency Inversion Principle, Interface Segregation Principle, and Liskov Substitution Principle articles for starters.

like image 110
SingleShot Avatar answered Mar 11 '23 03:03

SingleShot