The class has 6 fields, each field must be checked for the correctness of the value: whether the parameter value is not negatively checked. I understand that the values can be checked directly in the constructor, if exceptions are thrown, throw exceptions. Question: how to organize the validation of parameters, I mean, is there a pattern or some other pattern for this operation?
- And what should be with those who did not pass the test - to be assigned a default value, a warning is issued, an exception is thrown or what? - pavlofff
- @pavlofff, there should not be an object that contradicts logic, for example, a triangle with a sum of 1000 angles. What do you mean by a warning? - bsuart
- oneyou can use such a thing ru.stackoverflow.com/a/602629/10353 - Artem Konovalov
|
1 answer
I would do this:
public class TestClass { private int x; private int y; public TestClass(int x, int y) { if (isParamNotValid(x) || isParamNotValid(y)) throw new IllegalArgumentException("Input parameters are not valid! Need to be bigger zero"); this.x = x; this.y = y; } private boolean isParamNotValid(int p) { return p < 0; }} |