A question about Java class structure.

In a project that belonged to a long time ago, the service class describing the business logic as shown in the example below always had a one-to-one configuration of interface and the class that implements it.

SearchInputService .java

I use interface for polymorphism, but I don't understand why I need to use interface if there is only one class that implements the interface as shown above.
Why do you think the reason for such an implementation?
I am sorry that it is not very specific but I would appreciate your reply.

  • Answer # 1

    I have two reasons.
    However, as I will explain later, I always think that separating interface and implementation is redundant.

    1. Useful for testing

    For example, if there is a function to access the database, if it is set as an interface, it can be tested by changing the implementation to a mock only during testing. (Well, it can be achieved by inheritance ...)

    2. Classes and interfaces are not binary compatible

    Classes and interfaces are not binary compatible (source compatible), so if you don't use interface first, you may not be able to change it later. It is an article of my site, but it describes the method that was specifically verified.

    Java classes and interfaces are not binary compatible

    I wrote two reasons, but 2. rarely happens. Even if it is divided, I think that only some classes are enough. There is also a high-quality mock library for 1. On the other hand, it is easier to test using real DBs without using mock.

    So it's redundant to separate the interface and implementation every time, so I can refactor it when necessary.

  • Answer # 2

    In my opinion, when I just started Java, I made Interface and Implement in pairs. The class that was automatically generated by the framework used was like that, and at that time I had a question like Mr. poyota, but I was deeply conscious of such a thing. did not.

    Now, we create only what we need for Interface and implement it as a class that can exist alone if it is not necessary. I feel that people are now aware of what implements the interface and what inherits with extends.