search

Home  >  Q&A  >  body text

java - 我们该信任接口的返回值吗?

先举个例子

public Result doSomething(String balabala);


public class Result{
    private Long productId;
    ....
}

上面接口是其他部门的程序员提供给你的。没有文档,接口没有注释。
首先,我调用这个接口,

Result result= doSomething("fuck");

调用之后,我要返回的productId再去请求其他接口,做其他一些事情。

问题来了:

  1. 对这个返回的result,你是直接result.getProductId(); 还是先判断一下,result!= null 然后再result.getProductId();那productId又是Result里的引用类型,你拿到productId要不要再productId != null
    ,Result还有其他的引用类型,是不是我每用一个非得判空?

可能每个人的习惯不一样,比如写那个接口,有的人是哪怕什么信息都没有返回,也返回一个空的result。有的人是如果没有信息返回就返回null。如果只要是引用类型,我都判断是否为空,是不是显得“过于谨慎”了。文档,注释也不可能规定的那么细,程序员之间的约定吧,那一个几百人的团队,难免会有不遵循约定的。你们是如何处理的?

又比如一条记录,业务上规定,productId不可能为空的,但是这条记录的插入涉及到两条sql语句,一个程序员的失误没有保证原子性,导致productId为空的记录被插入进去了。这时候,我一旦涉及到处理productId,没有判空,则很有可能导致异常

迷茫迷茫2807 days ago1361

reply all(15)I'll reply

  • 黄舟

    黄舟2017-04-18 09:56:07

    Use kotlin to write.

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-18 09:56:07

    I think this problem lies in the definition of the interface first.

    If the interface is clearly defined and does not return null, then there is no need to handle the case of null return value. Otherwise, it needs to be dealt with.
    If a problem occurs, you can file a bug with the other party and ask the other party to fix it.

    If there is no clear definition, or the interface provider is not from our company, or the other party has problems and cannot correct them in time, then you can only make some defensive code yourself. And you can wrap the interface on your own side to ensure that null is not returned.

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 09:56:07

    I can tell you very clearly just by reading the title, I can’t believe it. Even if your interface definition is standardized and transparent in the early stage, believe me, if you don’t do fault tolerance and exception handling, you will still cry in the end~~

    reply
    0
  • 高洛峰

    高洛峰2017-04-18 09:56:07

    Since it is an interface, the interface provider must provide clear descriptions of parameters and return values. This is common sense for the interface provider. If that's not possible, you should know what to do.

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 09:56:07

    The definition of the interface must clearly state when null is returned and what returning null means.

    If you don’t make it clear, ask the other person to make it clear. Once it’s made clear, just do it. If you still have problems after following these instructions, it’s usually the other party’s problem and ask them to correct it.

    reply
    0
  • Cancelreply