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)

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();

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"


set{Property} definitely. It tells what the method is doing. Imagine your property is called visible or encoding or algorithm. Not using set won't make any sense.

You can use more descriptive action names, which differ from the name of the property. For example:

visible -> show(..) encoding -> encode(..) read > makeReadable(..) name -> giveName(..) ("name" is a verb, but is ambiguous)


The set clearly interferes with clarity. They aren't really beans-like method, so I say drop it.

I would also suggest separating the builder from the product. Prefer immutability in the product.

If you have flags, I think it much better to use booleans rather than pairs of methods. The Java library made this change going from 1.0 to 1.1. However, I still don't like booleans. There is not much higher-level meaning in true and false. enums are better. Better yet, if you are talking about something which can be considered a set (as in the example), then use Set (probably implemented as EnumSet).


Need Your Help

Beginner Sockets with .NET/C# : Request desktop icons

c# networking tcp client-server

I'm developing a little application which will connect to a remote machine, and return to the client a list of the remote's desktop icons.

Grey scale image to Monochromatic scale?

c++ image colors scale grayscale

I'm a beginner programmer, I know C and some C++, but never programmed GUI's, only console applications