创建新对象并将其返回或在return语句中创建新对象更好吗? [英] Is it better to create a new object and return it or create the new object in the return statement?

查看:125
本文介绍了创建新对象并将其返回或在return语句中创建新对象更好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

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

而不是:

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

一个比另一个更有效吗?

Is one more efficient than the other?

推荐答案

在返回之前分配给临时变量使您有机会在newPerson()中进行错误检查和更正。返回新调用需要newPerson()方法的调用者捕获并从错误中恢复。

Assignment to a temporary variable before returning gives you a chance to do error checking and correction from within your newPerson(). Returning the new call requires the caller of your newPerson() method to catch and recover from errors.

这篇关于创建新对象并将其返回或在return语句中创建新对象更好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆