Kevin Meier
Kevin Meier

Reputation: 2590

Java / Database-Query: null or Excpetion?

I have a design question. In a small java application we have some classes which are used to access the (mysql) database. There exists the following method:

public Integer getPvpBotId(int userId);

It returns the BotId of the PvpBot of the given user. Not every user has a PvpBot. And a Bot itself is a relatively big object, so i dont like to load the full object and return it, just the id.

Unless the PvpBot exists, should i return null? (which i do currently with the Integer instead of int)

Or should i throw an exception?

I ask this, because i like to produce code which is as clean as possible.

regards

Kevin

Upvotes: 0

Views: 56

Answers (4)

sroidl
sroidl

Reputation: 100

Consider using the Optional type of the guava library . It is designed specifically for your scenario. Instead of returning null, you would return Optional.absent(), thus signaling the user of your method the absence of your Bot in a well typed manner and avoiding possible null pointers.

Your code would look like this:

public Optional<Integer> getPvpBotId(int userId) {
  if (userHasBot()) { // insert your routine here
    return Optional.of(botid);
  }
  else {
    return Optional.absent();
  }
 }

with the caller being able to distinguish:

 if (getPvpBotId(12).isPresent()) {
   Integer botId = getPvpBotId(12).get();
 }
 else {
   // Not Bot is present...
 }

Upvotes: 1

Ceiling Gecko
Ceiling Gecko

Reputation: 3186

I would say that if at the point of where the getPvpBotId(int userId) is called the component is heavily dependent on the BotId e.g. it's a module for handling PvpBot related stuff and/or the BotId is expected, you'd throw an exception.

If at the point where the BotId is retrieved the PvpBot related data only is a part of the component (e.g. displaying additional information/functionality if the user has a PvpBot attached.) then the function should return null instead of an exception.

Upvotes: 1

Germann Arlington
Germann Arlington

Reputation: 3353

Generally, raising exception involves extra effort (on JVM part) so I would say return a value to indicate missing record - i.e. when ID does not exist, and raise an exception if your DB connection was down at the time

Upvotes: 1

npinti
npinti

Reputation: 52185

As you say in your question, not all users will have a bot, thus it is to be expected to encounter some null values.

I think that in this case, you could return null, since not finding a bot does not seem to be an exceptional case.

It is important though that you state what you return an why, so as to avoid null pointer exceptions.

Upvotes: 1

Related Questions