My team mates introduce me to new practice writing method which will not return void.
public class Test {
public Test doCalculations() {
//code
return this;
}
public Test appendTitle(String test) {
//code
return this;
}
}
Instead of returning void they suggest to return object itself. One of the advantage of this aproach they say, you can chain methods.
Instead of writing:
while(1) {
test.appendTitle("aaa");
test.doCalculations();
map.add(test);
}
You can write more elegant code:
while(1) {
map.add(test.appendTitle("aaa").doCalculations());
}
What could be disadvantages of this aproach? Do you suggest to include it in daily use?
1) A Void Function Can Return: We can simply write a return statement in a void fun(). In fact, it is considered a good practice (for readability of code) to write a return; statement to indicate the end of the function.
Yes, we can return multiple objects from a method in Java as the method always encapsulates the objects and then returns.
Yes, a class can have a method that returns an instance of itself. This is quite a common scenario.
To avoid the problem of duplicated bugs, never reuse code by copying and pasting existing code fragments. Instead, put it in a method if it is not already in one, so that you can call it the second time that you need it.
I would say it is not a good practice. By looking at the method signature that returns an object, how can I know if it is a entirely new instance that is being returned or the existing one being returned.Note that in cases of immutable classes modified methods do return a new instance of the class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With