Java返回Object /修改对象(编码指南) [英] Java return the Object/modify the object (coding guidelines)

查看:520
本文介绍了Java返回Object /修改对象(编码指南)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个方法填充/修改一个对象,最好是返回对象或保持返回类型为void,并且该方法将通过其引用修改对象?

If a method populates/modifies an object, would it be preferable to return the object or to keep the return type as void and the method would modify the Object through its reference?

public Obj populate(Obj o)
{
....
return o;
}

public void populate(Obj o)
{
....
}

我知道这是一个小问题,但哪一个是最喜欢的?

I know this is a trivial question, but which one is the most preferred?

推荐答案

我取决于你的风格,但返回的一个优点:你可以调用 populate(o).doSomethingElse(); 方法调用。

I depends on your style, but one advantage of returning: you could call populate(o).doSomethingElse();, i.e. you can chain method calls.

看看 StringBuilder 如何做,例如, $ c> new StringBuilder()。append(a)。append(b)....

Have a look at how StringBuilder does that for example, which allows things like this new StringBuilder().append("a").append("b")....

这篇关于Java返回Object /修改对象(编码指南)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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