Baz
Baz

Reputation: 13145

Purpose of "with" methods in class

I'm looking at class called Product which includes the following:

@JsonProperty("name")
public void setName(String name) {
    this.name = name;
}

public Product withName(String name) {
    this.name = name;
    return this;
}

what is the purpose of the withName method and how is it used? Why not just do:

Product p = new Product();
p.setName("foo");

Upvotes: 1

Views: 91

Answers (3)

Andrea Grossi
Andrea Grossi

Reputation: 92

It is used to get a reference to an object by its name so that method call can be chained with other calls on same object.

Example: withName(String name)

Upvotes: 1

Chris
Chris

Reputation: 23181

You could do either way, but the first is trying to provide a "fluent" api so you can chain together a number of calls... something like:

Product p = new Product().withName("blah").price(1234).quantityOnHand(35);

It is similar to a builder where you may have another object that presents the api and then ends the chain with a "build()" call that produces the instance of the class you're building:

Product p = ProductBuilder.newBuilder().withName("blah").price(1234).quantityOnHand(35).build();

Upvotes: 1

GhostCat
GhostCat

Reputation: 140573

The major difference is that the with method returns the instance of the object is called on.

That allows for "fluent" calls like

 someProductBuilder.withName("bla").withPrice(100)...

In that sense: an informal convention to distinguish ordinary setters from those that allow for fluent usage by returning the affected object.

Upvotes: 6

Related Questions