Should a retrieval method return 'null' or

2018-12-31 18:26发布

I have a method that is supposed to return an object if it is found.

If it is not found, should I:

  1. return null
  2. throw an exception
  3. other

30条回答
看风景的人
2楼-- · 2018-12-31 18:39

Use the null object pattern or throw an exception.

查看更多
萌妹纸的霸气范
3楼-- · 2018-12-31 18:39

referring only to the case where null is not considered an exceptional behavior i am definitely for the try method, it is clear, no need to "read the book" or "look before you leap" as was said here

so basically:

bool TryFindObject(RequestParam request, out ResponseParam response)

and this means that the user's code will also be clear

...
if(TryFindObject(request, out response)
{
  handleSuccess(response)
}
else
{
  handleFailure()
}
...
查看更多
素衣白纱
4楼-- · 2018-12-31 18:41

Be consistent with the API(s) you're using.

查看更多
素衣白纱
5楼-- · 2018-12-31 18:42

Unfortunately JDK is inconsistent, if you trying access non existing key in resource bundle, you get not found exception and when you request value from map you get null if it doesn't exists. So I would change winner answer to the following, if found value can be null, then raise exception when it isn't found, otherwise return null. So follow to the rule with one exception, if you need to know why value isn't found then always raise exception, or..

查看更多
步步皆殇っ
6楼-- · 2018-12-31 18:43

If null never indicates an error then just return null.

If null is always an error then throw an exception.

If null is sometimes an exception then code two routines. One routine throws an exception and the other is a boolean test routine that returns the object in an output parameter and the routine returns a false if the object was not found.

It's hard to misuse a Try routine. It's real easy to forget to check for null.

So when null is an error you just write

object o = FindObject();

When the null isn't an error you can code something like

if (TryFindObject(out object o)
  // Do something with o
else
  // o was not found
查看更多
只若初见
7楼-- · 2018-12-31 18:44

Or return an Option

An option is basically a container class that forces the client to handle booth cases. Scala has this concept, look up it's API.

Then you have methods like T getOrElse(T valueIfNull) on this object thet either return the found object, or an allternative the client specifieces.

查看更多
登录 后发表回答