Suppose I have two different classes that need to print different things:

OrderManager wants to print the order history, and MenuManager wants to print perhaps a menu. Since both want to do a similar function (but actual implementation is different), is it advisable to use an interface like this? The problem is that the function "print" is not very well-defined and self-explanatory as opposed to "printOrderHistory", and I can only implement the method with the exact name as defined in the interface.
Is there a workaround to this or am I using the interface concept wrongly? In fact, nothing seems to be stopping me from just defining their own print functions for each class without an interface...
CodePudding user response:
The idea with interfaces is to have a contract to fullfill. That means, that you have to you use method names and parameters defined in the interface when you build an implementation.
From my personal experience, it's always a bad idea to force an interface on classes, that are not similar, as in they do have a different purpose. While you could work with print() in both classes, it only makes sense if they are exchangeable in your code.
CodePudding user response:
This is the purpose of an interface! It defines a set of operations, and any class that implements this interface needs to implement these operations. This allows then to refer to a Printable object and call print(), knowing that it will perform as relevant for that object.
Your UML diagram, is therefore ambiguous: as OrderManager realizes (in java, "implements") Printable it should have its own print(). There are three solutions in UML and in Java:
Comply to the interface, as your diagram promises, and rename
printOrderHistory()intoprint(). This makes sense if there is only one meaningfull way to print and order manager, and if there are no other constraints.Add a
print()operation (in java, "method") toOrderManager(), that just forwards the call toprintOrderHistory(). But this looks like overcomplicated. It's justifiable only if the order manager would really e a printable, and ifprint()would add some relevant functionality such as selecting the right printing function depending on some factors.

