I want to write a method in java which receives an array of objects, checks for some compatibility and return a boolean value true if all meet, otherwise to return a string containing a message to inform user why some of the compatibilities don't meet. I came up with simplified version of my question as follows:
Suppose you wanna compare cars and in order that comparison make sense you wanna make sure all are of same class, same color, same make.
So what I am trying to get from this method are two:
1- are all care compatible? (boolean using return)
2- if not, why? so to inform user of the reasons(String using throw)
What is the best design pattern for this?
Below is one way of implementing it:
boolean areCarsCompatible(Car [] cars) throws CarException {
String errorMessage = "";
for(Car car:cars){
if (cars done have same color) errorMessage +="Cars dont have same color";
}
for(Car car:cars){
if (cars done have same make) errorMessage +="Cars dont have same make";
}
for(Car car:cars){
if (cars are not all of same class) errorMessage +="cars are not all of same class";
}
if (errorMessage.equals("")){
return true
} else {
throw new CarException (errorMessage);
}
}
The toString() method of Boolean class is a built in method to return the boolean value in string format.
Java Boolean equals() method The equals() method of Java Boolean class returns a Boolean value. It returns true if the argument is not null and is a Boolean object that represents the same Boolean value as this object, else it returns false.
A Boolean expression is a Java expression that returns a Boolean value: true or false .
It's a boolean result of an evaluation - true or false . If it's true, do something. Using it with return returns that boolean result to the caller.
to return both boolean and strings
Although you can do this in other (dynamic) programming languages, it's strongly recommended that you don't design your method like this in Java. In Java, types are statically checked and strict, you simply can't return two different types from the same method, and throwing an exception when you intend to return a string is, well, just an ugly hack.
A different matter would be throwing an exception with a message to indicate an error, that's a very common practice and within the good practices of the language. But notice that you wouldn't be "returning both boolean and strings", an exception is intended for error handling.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With