3

I thought a class is supposed to define, or give a blueprint, of attributes and methods for an object. And then, an interface is to provide a set of methods, as a contract for its clients. (and so a class also gives an interface as well, because a class also define a set of methods).

But say, if we have a class called Shape. Now we add an interface to it, called Moveable. Now we may have to add attributes to the class, such as velocity. But interface is only about methods, then how would we think about adding attributes to the class due to interface?

  • 1
    Possible duplicate of Attributes / member variables in interfaces? – scriptin Jan 3 '16 at 13:05
  • The short answer is "An interface has no state", or, more precisely, interfaces do not define any state. – scriptin Jan 3 '16 at 13:07
  • If you change "an interface is to provide a set of methods as a contract" to "... a set of methods and/or attributes ..." then the question being asked here seems to evaporate. Is there a specific reason you think it doesn't make sense to have "attributes" in an interface? Or why it wouldn't make sense for an "attribute" to be part of a contract? (whether it does probably depends on the language) Does scriptin's comment address that reason? – Ixrec Jan 3 '16 at 13:10
  • Implementing an interface by a class in regards to the available API is almost the same as only extending an already existing interface. By implementing an interface you provided two way of using your class, first, the more general contract, by only requiring the Moveable interface and hence not being interested in the Shape, or using the Shape itself, which also provides you the access to the Moveable interface. – Andy Jan 3 '16 at 13:19
  • I might think of Interface as just multiple inheritance, but just that we don't want to have the issues of multiple inheritance (such as if self doesn't have the method but grandparent does, and second parent has it too, which one should you use)... so if viewed that way, it may make sense to have new attributes for interface, as it really is a base class... but I think we just don't have the benefit of code reuse of be able to inherit all the attributes needed by an interface and need to define it ourselves – nopole Jan 3 '16 at 13:31
4

You should think of an interface as a requirement made by somebody else.

You should think of an implementation that meets the requirement as being a decision you make for your own class.

In most OO languages, class state is an implementation concern.

As such, a well implemented getVelocity is something that you need to provide behavior that meets somebody else's requirement. You may implement that requirement in any technique that works for you. If you want to store velocity as an integer, or compute it on the fly from a queue of recently sampled position and time events, that is your prerogative.

Sure, not having to constantly re-implement simple methods is convenient. There is a solution to this in many OOP languages -- the Mixin. Depending on the language, Mixins can have vastly different constraints, especially w/r/t state.

Java default impls, for example, have no state of their own but they can access the other methods of the interface. So you might be required to implement getVelocity, but all othe calculations involved with velocity could offer a default implementation.

Meanwhile, traits in Scala are so full featured it's common to see programs whose implementations are written almost exclusively in traits rather than classes (Concrete realizations are then provided by Objects and Case Classes)

In languages without mixins, delegation is a common solution, where the class that adopts an interface will also have a private member class that provides the behavior. The original class will still directly implement the interface's methods, but in the body of those methods will simply delegate the call to the private member.

1

Attributes like velocity are implementation details and therefore don't belong to interfaces. Interface doesn't dictate you to add attributes, it's the chosen implementation that does that. One implementation may use the velocity attribute and other would use the acceleration.

So you don't add attributes due to interface, you add attributes due to selected implementation. And it is usually the programmer who decides how to implement an interface, not the interface itself.

  • 1
    You can add to interface anything you want. – Andy Jan 3 '16 at 13:38
  • @DavidPacker, yes, you can, but I don't think it means that you have to add attributes into your implementation class. If the Moveable interface contains attribute velocity along with a getter and setter, then it is a poorly designed interface, I should say. And even in that case you don't absolutely need to add the attribute into your implementation class because you still need to reimplement both the getter and the setter. – name_no Jan 3 '16 at 14:00
  • @DavidPacker there is no requirement to add the getter or setter for velocity... – nopole Jan 3 '16 at 15:55
  • if both a class and interface provide a interface, then why does a class also defines a set of attributes, and an interface does not? Is it based of the practicality that we don't have multiple inheritance? – nopole Jan 3 '16 at 16:27
  • Because allowing direct access to attributes often considered a bad practice and violation of incapsulation, and therefore attributes are rarely made a part of an interface. – name_no Jan 3 '16 at 16:33
1

There's already a nice answer but I noticed this part:

I might think of Interface as just multiple inheritance, but just that we don't want to have the issues of multiple inheritance [...]

I'm guessing you're working in a language where the notion of "interface" is strictly stateless. I often find those somewhat heavy-handed and think multiple inheritance isn't quite as messy as some make it out to be.

Nevertheless, at a conceptual level, the stateless interface is often the most general, the most ideal from the contractual and maintenance point of view.

Robots With Wheels

For example, imagine I wrote a boatload of code using a robot interface which commanded robots to go to various places (rooms, buildings, countries).

If said interface included attributes like the idea that a robot has wheels, that would couple my requests to the notion that a robot has wheels. My requests would then only work for robots that have wheels (they might still be able to go to new locations using other means of transportation, but they would at least require possessing wheels to do it).

That degeneralizes the concept of a robot to one who at least possesses wheels, and likewise degeneralizes all the requests I've made for robots to go to new places which might span in the tens of thousands of lines of code, e.g..

Now let's say a new robot is introduced which has legs, or a jetpack, or a molecular transporter and really had no need for wheels at all. This spells trouble for all the existing robot classes and all the existing code using them through this interface. Now we're in a pretty awkward position of needing to rewrite a lot of code which we wouldn't be in if the interface/contract for robots was stateless.

Flexible Interfaces Allow Variety

In general, the most ideal interfaces from the standpoint of leaving code that is resilient to change will leave a lot of room for a rich variety of concrete implementations without violating the interface contract. Once state is introduced to an interface, it often very quickly degrades the richness and can significantly narrow the variety of possible solutions.

Should this be absolute forced in a language design? I don't know -- I'm biased as one who prefers languages that don't force this. Nevertheless, I think it's generally far better if we erred towards stateless interfaces. An attribute/state will far more quickly degrade the generality of your abstractions than functions.

But interface is only about methods, then how would we think about adding attributes to the class due to interface?

These are implementation concerns. If the goal of a class that implements a Movable interface is to move to new locations, you have all kinds of ways to implement it and also represent the data required to do so. Try to appreciate that flexibility/freedom.

Probably a concern here is that, after the dozenth class or so, you feel like you're duplicating a lot of the same kind of boilerplate to implement an interface. In that case, you can reach for an abstract base class potentially, or use composition (store a member which does a lot of the gruntwork), possibly static methods (maybe most gross, however, if it starts to look like nondescript helper functionality), etc.

But try to keep in mind how flexible the interface is as a result of it being stateless, of not mentioning such concrete details as part of its contract.

1

An interface can be thought of as representing a behavior, or a role, that one or more objects can exhibit.

A shape might be movable, as might many other things. With a movable interface, one can start working with things that are movable without regards to what they are.

If you realize that the internal implementation of your object needs to change, it doesn't affect the separate concept of a particular behavior (interface). If however, you realize the behavior needs to change, likely you will need to modify all those things (objects) that have that behavior.

If velocity is just an internal implementation detail of an object, it affects no interface (behavior). If however you realize the behavior the interface represents was incorrectly defined, and now requires velocity, you need to modify the interface and each object exhibiting the interface accordingly.

Hopefully, you can start to see that the object and the interface are two separate concepts. They are orthogonal to each other.

0

You don't create a class and then create an interface for it. That's getting it completely backwards. The creator of a class should never control the definition of interfaces that the class supports.

An interface is defined by someone outside the class. Someone says "I need an object here, and I don't really care at all what kind of object it is, as long as it has this set of capabilities". And that someone defines the interface.

Someone else might then come along and either they say "I want to create a brand new class that can be used when someone needs an object with that interface, and not for anything else", and create a class that very closely matches the interface and nothing else.

Alternatively they say "I have this instance here of a class that I wrote long time ago, and I would like that instance in a situation where an object with that interface is needed". And then they add everything needed to implement the interface to the class, possibly creating new methods that just call other methods that were already there but didn't match the requirements of the interface, or adding completely new methods.

Especially in the second case, the interface and its methods are not how instances of the class are usually supposed to be used; the interface implementation is specialised code to be able to plug instances into existing other code.

0

IMHO

I tend to prefer not to expose inner class variables, like in this code:

person.name="sampleName";
s = person.name;

I like to encapsulate things so consumers are not coupled to inner components of a class.

Than means I use getters and setters to access or change inner state, like this:

person.setName("sampleName");
s = person.getName();

That way I keep the members private or protected.

That explained, a valid interface could be:

public interface Person {
     public void setName(String value);
     public String getName();
     public void doSomething();
}

Which does imply some state in a class impementing it. Perhaps implementors will have a name class member of type String.

Bottom line:

Interfaces can in a way force implementors to have attributes, only not exposed in a public way but using getters and setters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.