Useless interfaces

后端 未结 25 1492
南笙
南笙 2020-12-14 01:42

Why would you ever use an interface if you are only going to have one implementation of it?

相关标签:
25条回答
  • 2020-12-14 02:36

    One situation for an interface for only one implementation: RMI. You have an object on one application and will use it from another app via RMI; you need to have an interface. That way you don't even have to include the implementation class on the calling app, which might save the calling app from including a bunch of J2EE stuff or external libraries that the implementation might use.

    Another reason: Today you only have one implementation, but tomorrow there may be something in the JDK or an external library that could lead to changing that implementation (maybe creating a new one). Your system could change and you need to add a new implementation while keeping the old one; some maintenance, etc.

    0 讨论(0)
  • 2020-12-14 02:38

    because you might end up having two or more in the future

    ADDITION After reading some of the comments: Object mocking: this would imply that you WOULD have more than one implementation of your interface, yoru mock IS another implementation.

    0 讨论(0)
  • 2020-12-14 02:39

    If I knew for a fact that there would only ever be one implementation I wouldn't create an interface. This falls under YAGNI, IMO.

    (Of course, it's rare that I know anything about the future for a fact...)

    0 讨论(0)
  • 2020-12-14 02:39

    When I work with someone else on a project, for instance if I do the front end (Web application for instance) and the other person does all the database work, we start by writing an API. The side that faces me is all about the problem domain: classes for User, Administrator, Employee, SKU or whatever. Then we can work independently; she implements all the interfaces and I write the code that uses them.

    0 讨论(0)
  • 2020-12-14 02:40

    If you will only have one implementation, I wouldn't do it. The arguments put forth here that you might have multiple implementations don't really stand up to close examination. If you do end up with multiple implementations, it takes about 5 seconds to extract the interface using either built-in Visual Studio tools or Resharper.

    So yes, YAGNI - don't complicate your life until you have to.

    0 讨论(0)
  • 2020-12-14 02:40

    In some cases, for visibility: you might want certain parts of the code to see the concrete class and have access to the setters, and some others to see only getters: give them access to the interface only.

    This cannot always be achieved with public/protected/private.

    0 讨论(0)
提交回复
热议问题