There are several things you can do:
Not the best practice, though, because the method's client will be forced to handle the possibly returned null (and if he doesn't, a NullPointerException can be thrown).
Your method would look like:
anObject getObjByID(int id){
for(anObject obj : objList ){
if (obj.getID() == id){
return obj;
}
}
return null;
}
In this case, the client will have to deal with the case of null results:
anObject result = getObjByID(someId);
if (result != null) {
//proceed
}
- Throw
IllegalArgumentException (or some other Exception)
You can throw IllegalArgumentException to denote there's no corresponding Node for the provided id. The client will be forced to handle the exception.
Your method would look like:
anObject getObjByID(int id) throws IllegalArgumentException {
for(anObject obj : objList ){
if (obj.getID() == id){
return obj;
}
}
throw new IllegalArgumentException("Invalid index");
}
and the client will be have to handle the exception:
try {
anObject result = getObjByID(someId);
//proceed
} catch (IllegalArgumentException e) {
//handle the exception
}
Java8 introduces the Optonal<T> class, which is something like an alien - it may or it may not exist. Specifying the return type of a method to be Optional<T> helps the client have the awareness that a return value may exist, or may not.
Your method would look like:
Optional<anObject> getObjByID(int id){
Optional<anObject> result = Optional.empty();
for(anObject obj : objList ){
if (obj.getID() == id){
result = Optional.of(obj);
}
}
return result;
}
The client will use this method like this:
Optional<anObject> result = getObjByID(someId);
if (result.isPresent()) {
anObject realResultObject = result.get();
}
TitleCasefor your classes. I.e.AnObject.