What is the best way [an a correct one] to check a value, lets say I need a user input in a certain range. Could I place this check inside a setter method? My setter would than be a boolean return type instead of void? Are there some "laws" against making the setter return something?

Thank you for any info.


Recommended Answers

All 6 Replies

Yes setting the value of a variable using a setter is the best way . But then you do not return a boolean value.

Setter should not return a value. It is against programming conventions.

public void setmyYVar(int y){
this.y = y;
//do nothing or set a pre-defined value.

You could use the getter in the places where you need the value. Do a null check before using the value in case of objects.

There is something to be said for throwing an 'IllegalArgumentException' if the data is invalid.

the setter can always return a value, if you write it like that, but a setter is ment to 'set' data, not to 'get' it.
a better way would be to throw an exception, as JeffGrigg suggests. alternatively, you could check the value of a getter , but this would be quite some overhead.

so, the options (as I see them)

// an age may only be between 0 and 80 (minimum and maximum range included)
print int age;

public void setAge(int age) throws IllegalArgumentException{
  if ( age < 0 || age > 80 )
     throw new IllegalArgumentException("Invalid age entered");
  this.age = age;

pro: it's impossible to set aninvalid value, and you'll always be warned if your application or user as sent an invalid value.
contra: you'll need to make sure you handle this exception correctly everywhere you call this setter

// an age may only be between 0 and 80 (minimum and maximum range included)
print int age;

public void setAge(int age) {
  if ( age >= 0 || age <= 80 )
     this.age = age;

public int getAge(){
  return this.age;

pro: you still won't be able to enter invalid values, and you won't need to add as much exception handling to your code
contra: if you ever forget about this, and you try to enter an invalid value, you won't realize that your age value did not change. also, if someone else ever uses this code, he may not be aware of any logic within the setter, so, unless everyone who uses this setter immediately after checks the value using the getter method, they have no way to be sure.

Member Avatar

It is VERY common for "setter" type functions (methods) in database programming.
Not so much in other languages.

For "method chaining" / "fluent interface" there's a pattern, including Builder Pattern, for having setter methods return 'this'.

Okay then. Im going to go and check those exceptions then. Thank you very much.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.