以下代码示例首选哪种样式?
class Player
{
Player() { this.id = UID.generate(); }
}
void fillPlayerData(Player player, PlayerRequest playerRequest)
{
player.name = playerRequest.name;
...
}
或
Player fillPlayerData(Player player, PlayerRequest playerRequest)
{
player.name = playerRequest.name;
...
return player;
}
void setErrors(Object object, List<Error> errors)
{
object.status = Status.ERROR;
...
object.addAll(errors);
}
或
Object setErrors(Object object, List<Error> errors)
{
object.status = Status.ERROR;
...
object.addAll(errors);
return object;
}
更新: 哪一个更适合在RxJava中使用:
Single<Object> returnObject(Object object)
{
return loadSingle
.doOnSuccess(objectResponse -> fillData(object, objectResponse))
.doOnError(e -> addErrors(object, e))
.toCompletable()
.andThen(Single.just(object));
}
Single<Object> returnObject(Object object)
{
return loadSingle
.map(objectResponse -> fillData(object, objectResponse))
.onErrorReturn(e -> addErrors(object, e));
}
答案 0 :(得分:1)
您拥有的方法类型基本上是修改参数。有三种情况可能
[案例1]传递的参数是(是)原始的
public void invoker(){
int x = 20;
int increment = 30;
x = getIncrementedValue(x,increment);
}
public int getIncrementedValue(int x, int inc){
return x+inc;
}
[案例2]传递的参数是(不)可变的
public void invoker(){
String x = "kk";
String y = nits;
x = getAppendedString(x,y);
}
public String getAppendedString(String a, String b){
a = a.append(b); // as Strings are non mutable hence this is not changed on the original passed object. The assignment of a also does not make any difference as it's local variable.
return a
}
[案例3]传递的参数是(是)可变对象引用。
public void invoker(){
Student s = new Student();
promoteStudent(s);
}
public void promoteStudent(Student s){
s.standard++;
// No need to return the object reference as same object has been modified and reference of the same is present with the invoker.
}
public class Student{
int standard = 1;
}
修改强> 注释中提到的另一个用例。在链接的情况下,返回相同的对象很有用。
public class Student{
String name;
int roll;
int standard;
public Student setName(String n){ this.name =n; return this;}
public Student setRoll(int n){ this.roll =n; return this;}
public Student setStandard(int n){ this.standard =n; return this}
public int getFees(){
return standard*2;
}
}
...
public void someMethod(Student s){
Int fees = s.setName("KK").setRoll(30).setStandard(10).getFees();
// Other lines of code ..
}