Is it bad practice to make a setter return "this"?
Utilizing a Fluent Interface that enables setters to return this
results in method chaining. This approach links method calls together, simplifying object configuration.
Here is a Practical example:
This strategy adds clarity and succinctness! However, it does diverge from conventional Java Beans void
setters. Ensure you apply this pattern with discretion, maintaining codebase consistency.
Applying Fluent Interface to Immutable Objects
For Immutable Objects, the withX
syntax is key for upholding Data Integrity, while still embracing the fluidity.
Introducing the Builder pattern
The Builder Pattern expands on the idea of method chaining. It simplifies complex object creation, removing the need for an over-complicated constructor.
A tip on a side: Naming setters as chainSetXyz
may reveal the purpose of the chaining.
The impact on tooling and team perception
Consider the Tooling and Libraries. Depending on your environment, some might not handle non-standard setter practices.
On the human side, some developers find chaining "ghastly", while others view it as the conduit to cleaner code. Knowing your team's preference is key in maintaining the code.
Steering clear of monster constructors
Long constructors with endless parameters are error-prone and challenging to read. Using this
in setters or a builder creates a much-needed shield against monster constructors.
Dispatcher's note: Managing code architecture
Watch out for a potential violation of the single responsibility principle (SRP) as each method does more than its intended role. Keep in mind the potential impacts on JVM optimizations.
The return journey: return type changes
Changing the return type of setters in the future may hinder chaining flexibility. Design with iterations in mind. Future you will appreciate it!
Alternatives: Factory or static methods
Factory or static methods offer an alternative pathway, providing clear object creation without verbose constructors or the need for complex fluent interfaces.
Was this article helpful?