I would like to use a class's set methods in the constructor in order to check the values to be initialized, throwing an exception if they do not comply with the constraints I set.
code example:
public class MyClass {
// Fields
private int number;
private String string;
// Constructor
public MyClass(int number, String string) {
setNumber(number);
setString(string);
}
// Set Methods
public void setNumber(int number) {
if (number<=0) { // Certain constrain for number
throw new IllegalArgumentException("Number must be positive");
}
this.number = number;
}
public void setString(String string) { // Certain constrain for string
if (string.equals("")) {
throw new IllegalArgumentException("string cannot be empty");
}
this.string = string;
}
public String toString() {
return String.format("Ordered %d x %s%n", number, string);
}
public static void main(String[] args) {
MyClass obj = new MyClass(8, "Souvlaki"); // Everything allright
System.out.println(obj);
try {
MyClass obj2 = new MyClass(-3, "Mousaka"); // Error in number argument
} catch (IllegalArgumentException exception) { // catch the exception
System.out.printf("Exception Caught: Number must be positive%n%n");
}
MyClass obj2 = new MyClass(4, ""); // Error in string argument
// Allow the exception to end program execution
}
}
Output:
Ordered 8 x Souvlaki
Exception Caught: Number must be positive
Exception in thread "main" java.lang.IllegalArgumentException: string cannot be empty at MyClass.setString(MyClass.java:23) at MyClass.(MyClass.java:10) at MyClass.main(MyClass.java:40)
The output is just what I wanted. First object created is initialized with appropriate values. Calling toString() method implicitly proves that. The second and third objects throw exception due to wrong initialization. The first exception is caught in order to allow the program to continue executing. The second exception is not caught in order to output the error message printed be the exception.
So everything seem to be right,but is this a good programing technique or it hides some bugs inside ?