0
\$\begingroup\$

quick question. I'm using Spring Boot and I created e.g. this class

public interface ProductService {

    Page<Product> getPage(Pageable pageable);

}

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductRepository productRepository;

    @Override
    public Page<Product> getPage(String name, Pageable pageable) {
        return productRepository.findAll(pageable);
    }
}

And this interface has only one implementation. And what is better to use interface with one implementation and inject interface or just create a class without interface and inject class?

\$\endgroup\$
1

1 Answer 1

2
\$\begingroup\$

The answer to this question may vary depending on the opinions regarding the various so-called "good practices".

If we take into account the dependency inversion principle (In SOLID principles), then we should always aim for our classes to depend on abstractions and not on implementations.

However we could also take into account the "KISS" principle (Keep it stupidly simple) and in this way I could tell you that if your application is not very large or complex, then do not use an interface.

Answering your question: "what is better to use interface with one implementation and inject interface or just create a class without interface and inject class?"

I recommend using an interface even if it has only one implementation, so in the future if the implementation changes, the class that depends on said interface will not be affected by said change, unless the interface signature changes as well.

\$\endgroup\$
3
  • 3
    \$\begingroup\$ I so much disagree with that, but this question does not belong on Code Review. \$\endgroup\$
    – Bobby
    Commented Nov 17, 2020 at 19:48
  • \$\begingroup\$ I would like to know your opinion, and why you disagree. I think it's important to know other points of view \$\endgroup\$ Commented Nov 18, 2020 at 13:49
  • \$\begingroup\$ Because, in my opinion, you're not gaining enough from doing that. You might have decoupled implementation from the interface, but if you need to change the signature you need to change it everywhere again. Additionally, the likelihood that there will be a different implementation, so that an interface is actually needed, is most of the time non-existent. An upside might be testing, but neither am I a fan of "pure unit-tests", in which you mock everything and only verify that methods have been called. At that point you're not testing functionality, you're verifying diffs of the source. \$\endgroup\$
    – Bobby
    Commented Nov 18, 2020 at 16:42

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