开发者

Best practice for return value if 3+ possible outcomes?

This is sort of a novice question, but I guess I just really don't understand what the best practice would be.

Basically, I have a method called "emailScan", which scans to see if an email already exists in a database. This c开发者_StackOverflow社区ould result in three possible outcomes:

  • Email does not exist
  • Email exists and is associated to a person
  • Email exists and is registered to a person

The question is, what should this method return? My thoughts:

  • It wouldn't return a boolean, obviously.
  • It wouldn't throw a checked exception, as none of these are exceptional conditions.
  • It could just return the raw Email object, and let the calling method make the determination of whether it is associated or registered.
  • It could return an Enum which represents the three outcomes

Any thoughts?


Enum is the way to go!

public enum EmailStates {
    DOES_NOT_EXIST,
    EXISTS_ASSOCIATED,
    EXISTS_REGISTERED
}


If you want to know which of the three cases holds, but don't want any more info (like the email itself), then an Enum (or even just an int, to keep things simple) is the way to go.


An enum seems best for this situation, in fact most situations where there are a small number of possible values:

public enum EmailAssociation { NONE, ASSOCIATED, REGISTERED }
public EmailAssociation emailScan(String email) { ... }


it could be an Enum or you could use exceptions, if you need to handle only one case (and return the others as errors). If this is not the case, I would have used an Enum


Getting data from a database and running some logic on the data are two different things. So returning only the email object seems the best way to go. Then you can reuse that function to search emails and do something else..

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜