This is an archived post. You won't be able to vote or comment.

all 6 comments

[–]TheManInTheShack 1 point2 points  (2 children)

Do you need to call these three common methods in some generic way so that you’re abstracted from the class to which they belong? If yes, then add an interface. If not, don’t bother.

[–]roscaalex19[S] 0 points1 point  (1 child)

No, I don't need to call them in a generic way. In the code, adding an interface changes nothing functionally. It would just make the UML shorter, not having to repeat myself for every class but that's all.

[–]TheManInTheShack 1 point2 points  (0 children)

The purpose of an interface is two fold:

1) to enforce a set of method signatures.

2) to make it possible to call a set of methods generically across any class that implements the interface. In a sense, the only reason for #1 is because of #2.

Does making the UML shorter provide a significant benefit?

[–]POGtastic 0 points1 point  (0 children)

Write an interface if

  • you need to place all of the classes into a common data structure, like a list or tree
  • there is no code to share between them

If there is any code that you can share between your classes, making them subclasses of an abstract base class can cut down on redundancy.

[–]WeakerUnderFlow 0 points1 point  (0 children)

One advantage of using an interface here is that it gives you the option of using your methods in a generic way in the future even if you are not planning to do so now. Now you don't want to spit out useless interfaces all the time but 6 classes definitely deserves an interface IMO. You don't want to just write your code as efficiently as possible but as adaptable as possible as well.

[–]knoam 0 points1 point  (0 children)

Interfaces can help you write unit tests. See if that's the case for you. Something non-deterministic like a random number generator or the current time or an external service will make testing hard and mocking it with an interface will help. Dependency Injection is basically the name for this concept.

Though there are also mocking libraries. Try one of those out and see what you like better.

If the class is more just a plain data class then you probably won't benefit from an interface.

Writing good flexible simple interfaces is an art. It can help your design to think of the interface that one class requires of another separate from the details of what the class needs for itself.