0

I am currently working on a project where I want to be able to create a options object by dynamically setting its properties on creation.

This made me come up with this type of constructor-setter combination:

Options options = new Options()
                .fontSize(12)
                .color(Color.RED)
                .showLabels(false);

Which would be equivalent to the less sleek looking:

Options options = new Options();
options.setFontSize(12)
options.setColor(Color.RED)
options.setLabelVisibility(false);

I have already seen something similar in Spring where you sometimes configure settings like this:

protected void configure(final HttpSecurity http) {
    http
        .antMatchers("/auth/admin/*").hasRole("ADMIN")
        .antMatchers("/auth/*").hasAnyRole("ADMIN","USER");
}

This made me wonder wether it is something that is commonly used and perhaps is some kind of design principle that has a name. Is this the case?

dasdawidt
  • 13
  • 5
  • Pretty sure what you're looking for is a Fluent API/Fluent Interface: https://en.wikipedia.org/wiki/Fluent_interface – JustAnotherDeveloper Jul 08 '22 at 21:03
  • 3
    Or in this case also the *builder pattern*. – MC Emperor Jul 08 '22 at 21:05
  • In pure Java, this is normally a _builder_ as @MCEmperor said. Groovy provides some convenient syntax in both its constructor-setter forms and `.tap` closures. – chrylis -cautiouslyoptimistic- Jul 08 '22 at 21:07
  • This is also called "wither methods" (because often you could name such methods: `withFontSize`, `withColor`, `withLabelVisibility`). – Jesper Jul 08 '22 at 21:09
  • Are you using Lombok? You can annotate the class with `@Builder` and then do something quite similar: `Options.builder().one(value).another(value).build()`. – David Conrad Jul 08 '22 at 23:14
  • Currently I'm just returning `this` at the end of each method, which works fine. The "wither" approach is probably the closest to what I'm doing, the builder would be more common. Would you consider it bad style to do it like I do? – dasdawidt Jul 09 '22 at 11:28

0 Answers0