Smooth Interface Method Names

I have a Permissions class in Java with free-style methods:

 somePermissions.setRead(true).setWrite(false).setExecute(true) 

The question is whether I should call these methods set{Property} or just {property} . The latter will look like this:

 somePermissions.read(true).write(false).execute(true) 

If I consider these methods separately, I would expect read something, but, on the other hand, it is closer to the intention of having something like named parameters, for example, in Scala:

 Permission(read=true, write=false, execute=true) 
+7
java scala naming fluent-interface
source share
4 answers

set{Property} better than just {property} for passing intent. However, since your examples are simple logical properties, perhaps a cursory interaction is even better:

 somePermissions.AllowRead().DenyWrite().AllowExecute(); 
+7
source share

This is a classic problem with smooth interfaces. Although I agree with @Bozho that setRead () is more self-explanatory, the goal in fluent interfaces is to make the whole "sentence" readable, as opposed to making individual method calls readable.

So I would go further. What about:

 somePermissions.readable().nonWritable().executable() 

See also Martin Fowler post on this topic. He says: β€œCreating a free API like this leads to an unusual API habit”

+6
source share

set{Property} definitely. He reports what this method does. Imagine your property is called visible or encoding or algorithm . Do not use set does not make sense.

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

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

+5
source share

set clearly discourages clarity. They are not like beans-like method, so I say "drop it".

I also suggest separating the builder from the product. Prefer the constancy of the product.

If you have flags, I think it's much better to use boolean variables rather than pairs of methods. In the Java library, this change has changed from 1.0 to 1.1. However, I still don't like booleans. true and false do not have many higher level values. enum better. Even better, if you are talking about something that can be considered a set (as in the example), use set (possibly implemented as an EnumSet ).

+1
source share

All Articles