jon lee
jon lee

Reputation: 887

Whats the name of this pattern and is frowned upon?

In Java, I see a lot of libraries lately that have classes with methods that always return the instance of the class so you can can call multiple methods without needing separate lines of code. For example:

public class Resource{

  public Resource path(String path)
      //execute some code
      return this;
  }

So you can do things like this

new Resource.path("1").path("2").path("3")

Rather than the verbose:

public void path(String path)

Resource r = new Resource();
r.path("1");
r.path("2");
r.path("3");

Is there a name to this pattern and is it good/bad practice?

Upvotes: 2

Views: 137

Answers (1)

janek
janek

Reputation: 184

It's called fluent interface pattern.

Often applied in builder pattern aka fluent builder.

http://www.martinfowler.com/bliki/FluentInterface.html

As to second part of the question:

Pros:

  1. Code readability and conciseness - it reflects what the code really does, like DSL

Cons:

  1. Problems with debuging
  2. Problems wih logging
  3. The command query separation mentioned in the link above gets broken

For more: http://en.wikipedia.org/wiki/Fluent_interface

The are probably some more aspects I didn't cover though

Upvotes: 10

Related Questions