#restrictions on fields?

1 messages · Page 1 of 1 (latest)

wispy matrix
#

When it comes to setting values of field of an object, it could either be done via constructor or using getters/setters. I'm thinking is there a more preferred way or it doesn't matter what we do? Suppose i don't want the fields to be negative. How should i go about it?

iron surgeBOT
#

<@&987246399047479336> please have a look, thanks.

iron surgeBOT
#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

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.

mossy dawn
#

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

wispy matrix
#

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

mossy dawn
#

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);

wispy matrix
#

like this?

mossy dawn
#

IllegalArgumentException is the idiomatic exception

wispy matrix
#

oh lol i forgot the name but yea that one

mossy dawn
#

also, u should provide the current value in the exception

#

otherwise its hard to debug

#
private static void requirePositive(int x) {
  if (x < 0) {
    throw new IllegalArgumentException("Must not be negative, but was: " + x);
  }
}
wispy matrix
#

oh

#

now i can use this method in my setters

#

or anywhere i'd like a positive value

#

this is much better, thanks

#

i see how constructors are valuable when it comes to immutable classes