Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

method names with fluent interface

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)
like image 442
deamon Avatar asked Mar 19 '10 09:03

deamon


People also ask

What are fluent methods?

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.

What is the fluent user interface?

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.

What is fluent interface in Java?

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.

What is fluent builder?

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.


2 Answers

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();
like image 50
Paolo Avatar answered Oct 04 '22 06:10

Paolo


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"

like image 40
Itay Maman Avatar answered Oct 04 '22 07:10

Itay Maman