Senior
What code is easy to cover with tests? Name at least three criteria of well-testable code.
sobes.tech AI
Answer from AI
Well-tested code usually has the following characteristics:
- Modularity and low coupling — code is divided into small, independent components or functions, making them easier to isolate and test.
- Clean and clear interface — functions have well-defined inputs and outputs, without hidden dependencies.
- No side effects — functions do not alter global state or external resources unnecessarily, which facilitates predictability and repeatability of tests.
Additionally, it is useful to:
- Use inversion of control and dependency injection to replace external components in tests.
- Implement good logging and error handling to simplify diagnostics.
An example of a function that is easy to cover with tests in Java:
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
Such a function is easy to test because it:
- Does not depend on external state.
- Has a simple and clear interface.
- Returns predictable results.