When programming in Spring/Spring Boot, it's a common practice to have every service/component implement an interface, for example:
public interface IAdder {
int add(int a, int b);
}
@Service
public class Adder implements IAdder {
public int add(int a, int b) { return a + b; }
}
Why do I actually need to write that interface if I don't plan on having multiple implementations for "Adder" functionality?
One common answer to that question is "you'll need it for mocking in your unit tests". To that, I can answer - not really. I can mock the adder using every possible mocking framework you can think of (Mockito, for example):
@Autowired
IMultiplier multiplier; // Class under test
@Mock
IAdder adder;
@Test // Assuming I implement multiplication by multiple additions
public void multiplicationTest() {
// Arrange
when(adder).add(3, 3).thenReturn(6);
// Act
int result = multiplier.multiply(3, 5);
// Assert
verify(adder, times(4)).add(3, 3);
assertThat(result).isEqualTo(15);
}
Having said that, what advantage can the IAdder interface provide for me?