#restrictions on fields?
1 messages · Page 1 of 1 (latest)
<@&987246399047479336> please have a look, thanks.
While you are waiting for getting help, here are some tips to improve your experience:
If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.
Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.
well, it obviously always depends on the exact situation. like, suppose there is a game and it has a stop() method, which eventually will set a field isRunning to false.
i wouldnt call this a setter method, yet it modifies a field.
but if ur thinking about classic "data classes", such as a Person with name and age, constructor and setters are just the most natural thing to have
although, in general, u would prefer immutable classes. so no setters, just the constructor
that said, validation should be made whenever u modify it
so constructor and setter
to avoid duplication, u can let the constructor use the setter
and then only have the validation in latter
ok so constructor is more for default values and things, but when modifying we should do the validation in setter
i don't often see code where they use setters in constructor usually or maybe i saw bad code, is it always recommended to use setters in constructor to avoid duplication? or would that depend on use case
so it would be something like this
duplication is almost always bad
if u duplicate the check in setter and constructor, thats bad
btw, those checks are kinda bad
validation at this point is supposed to throw
and not defensively say "u did a mistake" and then continue
this should have happened before that point already
attempting to call a setter with wrong values is incorrect usage and should result in an exception
that said, u already have duplication here
of the pattern "if < 0 ... no negative allowed"
so id create a method
requirePositive(length);
like this?
IllegalArgumentException is the idiomatic exception
oh lol i forgot the name but yea that one