Is it better to create a new object and return it or create the new object in the return statement?

后端 未结 6 1905
盖世英雄少女心
盖世英雄少女心 2021-01-05 12:24

For example:

public Person newPerson() {
  Person p = new Person(\"Bob\", \"Smith\", 1112223333);
  return p;
}

as opposed to:

<         


        
6条回答
  •  花落未央
    2021-01-05 13:14

    In a sane world, they will compile to exactly the same bytecode, so they are identical as far as performance is concerned. Then the only difference is for humans:

    Creating a temporary variable makes debugging slightly easier: you can put a breakpoint on the return statement and inspect the value of p. In the one-line version, this is harder to do.

    Doing it in one line eliminates a variable, reducing complexity, making the code slightly easier to read.

    In practice, I would write it in one line, and in the worst case I create a temporary variable if I run into the debugging issue. Besides, aren't unit tests supposed to eliminate the need for debugging? :-)

提交回复
热议问题