I have a Permissions
class in Java with methods in fluent style like this:
somePermissions.setRead(true).setWrite(false).setExecute(true)
The question is, whether I should name these methods set{Property}
or only {property}
. The latter would look like this:
somePermissions.read(true).write(false).execute(true)
If I look at these methods separately I would expect that read
reads something, but on the other hand it is closer to the intention to have something like named paramaters like in Scala:
Permission(read=true, write=false, execute=true)
A fluent interface is an object-oriented API that depends largely on method chaining. The goal of a fluent interface is to reduce code complexity, make the code readable, and create a domain specific language (DSL). It is a type of method chaining in which the context is maintained using a chain.
A collection of UX frameworks for creating beautiful, cross-platform apps that share code, design, and interaction behavior. Build for one platform or for all.
In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL). The term was coined in 2005 by Eric Evans and Martin Fowler.
Fluent builder pattern is a style of coding which force the developer to create the object in sequence by calling each setter method one after the another until all required attributes are set.
set{Property}
is better than just {property} for conveying intent. However since your examples are simple boolean properties, an even better fluent interfance might be:
somePermissions.AllowRead().DenyWrite().AllowExecute();
This is a classic problem with fluent interfaces. While I agree with @Bozho that setRead() is more self explanatory, the objective in fluent interfaces is to make the whole "sentence" readable as opposed to making individual method calls readable.
Thus, I would go a step further. How about:
somePermissions.readable().nonWritable().executable()
See also Martin Fowler's post about this topic. He says: "Building a fluent API like this leads to some unusual API habit"
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