Alternatives to returning NULL

2020-02-24 12:02发布

   /**
     * Returns the foo with the matching id in this list
     * 
     * @param id the id of the foo to return
     * @return the foo with the matching id in this list
     */
    public Foo getFoo(int id)
    {
        for (Foo foo : list)
        {
            if (foo.getID() == id)
            {
                return foo;
            }
        }

        return null;
    }

Instead of returning null when foo is not found, should I throw an exception? Does it matter, and is there a "best practices" idiom on the subject? By the way, I know my example is a bit contrived, but I hope you get the idea...

Thanks.

EDIT

Changed code to get Foo based on id to better illustrate a real-world scenario.

15条回答
迷人小祖宗
2楼-- · 2020-02-24 12:41

Best pactice would be to say in the Javadoc that null is return when no match is found.

Another approach might be to return a List of matches which could be empty (and could have more than one) However I don't like this approach.

Another approach might be to return a NULL_FOO of type Foo value.

I would prefer to just return null.

One way around this is to look at what are you going to do with the value and enrich the function so that the returned value is used in the method and not returned. e.g. if you are going to call a method with the value, just call it in the function which avoids the need to return anything.

查看更多
Rolldiameter
3楼-- · 2020-02-24 12:42

I prefer returning null. This is a perfectly fine result to return from a method, and your code that calls the method should handle null values appropriately. That might mean throwing an exception in your calling code, but I wouldn't do it in this method.

This way, if someone else wants to call your method down the line, they can handle null values differently than you if they choose. If you threw and exception it could potentially force another programmer to alter their code in a way different than what they intended.

Of course, there are some cases where it would make sense to throw an exception if something is null (like, a connection object or something like that, that you actually need to have a value and if you don't then that means something is wrong). But, as a rule of thumb, you should be fine returning null in most cases.

查看更多
等我变得足够好
4楼-- · 2020-02-24 12:42

I think it's a matter of taste and in this case it also depends on if the list may contain null values. If the list may contain null values, null would also be a valid method argument and you would need to distinguish between returning null (e.g. null was passed, found and returned) or telling the method caller that the passed null value was not found.

查看更多
劳资没心,怎么记你
5楼-- · 2020-02-24 12:46

This might not answer your question directly but it comes from a few remarks I've gotten from Stackoverflow members on similar topics.

Instead of returning null when foo is not found, should I throw an exception? Does it matter, and is there a "best practices" idiom on the subject? By the way, I know my example is a bit contrived, but I hope you get the idea..."

From what I gather, Exceptions should be thrown from a method when the Exception concerns a parameter given to the method. For example, a method accepting File instances would throw a NullPointerException or an IOException. This is following the idea that there's a contract between the caller and callee that the caller should sent valid objects and take care of them if they're invalid.

Also, you need to decide whether to handle pre- and postconditions. You can place a guard at the beginning of a method to handle parameters and this would save quite a bit of code. However, some view this as an incorrect approach in that some validation, say in a UI, should be done beforehand.

To finish off, it's perfectly valid to return a null object if the intent is to retrieve a a single instance. This is to paraphrase that an object was not found or doesn't exist. When it comes to groups of objects I think the convention is simply to return an empty Collection/List.

查看更多
太酷不给撩
6楼-- · 2020-02-24 12:48

I'd say it depends on your app and how the method will be used.

  1. If you expect a "not found" result happen frequently enough that it could negatively affect performance*, then return null, and check for it in the caller.
  2. If "not found" results will be relatively rare or will cause you app give up on the request, then throwing an exception would be fine. Exceptions could make your code easier to read, as you can then guarantee a successful return will produce an object, so you don't have to null-check it.

I subscribe to the opinion that exceptions should be used for exceptional conditions, which is a superset of error conditions. I also have adopted Spring/Hibernate's preference for unchecked exceptions, which avoids burdensome try/catch logic.

* There is not much performance overhead from using exceptions vs. returning null. I just did a quick test, it takes 4ms to call a method a million times that returns null, and only 535ms to another method million times that throws an exception.

查看更多
可以哭但决不认输i
7楼-- · 2020-02-24 12:50

I'd say it depends on the semantics of your method.

Will foo be almost always found in the list? (for example, if it is a cache that holds a finite amount of objects). If so, then not being found might mean something has gone wrong -- some app initialization failed, for example, or the key is invalid -- and an exception might be justifiable.

In most circumstances, however, I'd return null. Maybe the client knows the object might not be there and has coded logic to handle that case; if you used an exception, that code would be much harder to read, understand, and maintain.

Some APIs actually provide two methods: a find method that may return null, and a get or load method that throws an exception.

Hmmm... when in doubt, err in favor of null :)

查看更多
登录 后发表回答