Search code examples
javaimmutabilityfluent

Naming methods that adds items to an immutable object with fluent style


Is there a best practice or commonly accepted pattern to name methods that "adds" something to a collection on an immutable object with fluent style for Java API?

Here is a code example:

public class GivenUUIDGenerator {
    private final ImmutableList<String> playbackUUIDs;

    public GivenUUIDGenerator(List<String> playbackUUIDs) {
        this.playbackUUIDs = ImmutableList.copyOf(playbackUUIDs);
    }

    public GivenUUIDGenerator howShouldINameThisMethod(String uuid){
        return new GivenUUIDGenerator(ImmutableList.<String>builder().addAll(playbackUUIDs).add(uuid).build());
    }
}

This is coming from a Pull Request on a project I'm developing, and we already had a discussion on the best naming option for this method, but being both french doesn't help to choose a good name.

I've tried to find prior art or best practices, here is what I've found so far:

Other suggestions I got:

  • original PR proposition: withAddedXXX
  • another proposition: withAdditionalXXX

Solution

  • I would suggest and, and not modify the original list. Therefore, you could have something like:

    GivenUUIDGenerator.with(originalList).and(a).and(b).and(c).generate();
    

    This is what the class would look like:

    public class GivenUUIDGenerator {
        public static GivenUUIDGenerator with(List<String> playbackUUIDs) {
            return new GivenUUIDGenerator(playbackUUIDs);
        }
    
        private final ImmutableList<String> playbackUUIDs;
    
        private GivenUUIDGenerator(List<String> playbackUUIDs) {
            this.playbackUUIDs = ImmutableList.copyOf(playbackUUIDs);
        }
    
        public GivenUUIDGenerator and(String uuid){
            return new GivenUUIDGenerator(ImmutableList.<String>builder().addAll(playbackUUIDs).add(uuid).build());
        }
    
        public ... generate() {
            // ... do here whatever it is you want to do with your list
        }
    }