views:

174

answers:

4

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)
+4  A: 

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)

Bozho
I totally agree...
pgras
+7  A: 

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();
Paolo
That's fine, but you8 should think about handling the case where someone chains nonsensically: `AllowRead().DenyRead()`
oxbow_lakes
+6  A: 

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"

Itay
+1  A: 

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).

Tom Hawtin - tackline