You have a lot of null checks (well, two at least), which I think leads to less readable code. Also, it shouldn't really be necessary to have them.
if (authToken == null)
this isn't really something this method should concern itself with. In my opinion, getUserFromDatabase
should handle that case (via IllegalArgumentException
, which is a RuntimeException
). Although it's a case that really shouldn't happen in the first place. Why would getAuthToken return null instead of throwing a not found exception?
You should also always try to reduce the level of nesting you have, to increase readability. If you have
if (something) { doSomething(); return;} else { doALotMore();}
write it as:
// we handle all the exceptional stuff here, and returnif (somethingWentWrong) { handleIt(); return;}// the expected code goes heretoDefaultStuff();
With those two points, your code would look something like this:
@ApiMethod(name = "getUserData", path = "get_user_data")public Bean getUserData(@Named("token") String token) { [...] try { authToken = ServerFacebookHelper.getAuthToken(token); } catch (NoConnectionException e) { response.setData("Exception occurred"); return response; } catch (InvalidTokenException ite) { response.setData("Token invalid, please log in"); return response; } catch (...) { ... } user = getUserFromDatabase(authToken); if (user == null) { user = registerUserInDatabase(authToken); // removed setData duplication } response.setData(user.getPersonalisedWelcome); return response;}
if (user == null)
also doesn't seem like a good way of handling it. Why is user null? Currently, we don't know, it could be a number of reasons (user not found, problems with the database conncetion, incorrect query, etc). This is why returning null for functionality is generally not a great idea, because the caller will have to guess quite a bit.
One solution would be to add a isUserInDatabase(authToken)
, but that would add additional db queries.
You could also throw a UserNotFound exception, but it doesn't seem like an exceptional situation, so that is also not ideal (at least in this situation; generally, not finding a user would be exceptional for a getUserFromDatabase
method).
Another option would be to add an exists
method to your user class, but again, that doesn't seem all that clean either.
The question is what the difference between registering and getting really is (and what data is set in user; for registering, this seems to only be the token, which means that you get an incomplete user object returned, which also doesn't seem ideal), and why you don't handle it in completely different methods (ie why getUserData
does something - registering a user - if the user doesn't exist already (instead of having another method for that)).