It is necessary specifically in the java bean framework model, but it s not mandatory in general.
You can have setter with no argument when they are meant to "swith" a value.
void setCheck()
could for instance be meant to set the "check" boolean attribute to true.
So even if it is not a "setter" in the java bean sense of the term, you can imagine setter used for other purposes.
Plus, according to section 7 of JavaBean specifications, a setter can have more than one argument, for instance for Indexed properties (An indexed property supports a range of values. Whenever the property is read or written you just specify an index to identify which value you want.)
void setter(int index, PropertyType value); // indexed setter
void setter(PropertyType values[]); // array setter
In your case, a valid approach would be to add a runtime exception to the signature of our function.
That way you do not put any unnecessary compilation-time exception checking for all of the other classes which are already calling your setter.
Or you could consider your property as a Constrained property and add a non-runtime exception.
Constrained property setter methods are required to support the PropertyVetoException.
This documents to the users of the constrained property that attempted updates may be
vetoed.
So a simple constrained property might look like:
PropertyType getFoo();
void setFoo(PropertyType value) throws PropertyVetoException;
which allows for VetoableChangeListener to be added if needed.
Regarding your snippet, it is "valid" but may not be optimal because (as said in this question):
- Validation should be captured separately from getters or setters in a validation method. That way if the validation needs to be reused across multiple components, it is available.
- It is better to fail fast (hence my proposition to add exception to the setter).