I was thinking about code structure and thinking about setters. They were used as invalid methods, so why not use any possible return value to include some new code structure?
My idea was to change all seters properties from void to instance reference so that we can do setters or something else in sequence. Here is an example:
public class MyClass { private int foo; private String bar; public MyClass setFoo(int foo) { this.foo = foo; return this; } public MyClass setBar(String bar) { this.bar = bar; return this; } }
Then in some other place in the code we could do:
... MyClass myInstance = new MyClass(); myInstance.setFoo(auxFoo).setBar(auxBar); ...
This allows you to set all the properties of the class on a single line, useful in conversion methods.
Or even:
... return myInstance.setFoo(auxFoo);
It was my goal, for example, to set the error property by returning it. This can simplify catch locking, for example.
EDIT: After some answers I need to add:
- The question is only about setters (not about doing this in all methods), and is not limited to the chain, but for other applications, such as the
return
example. - Can a change from void to something else create any problems? For example, Java Inspects.
- Can you see more advantages or disadvantages of this?
I was hoping to see some discussion.
source share