1

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");
Baz
  • 12,713
  • 38
  • 145
  • 268

3 Answers3

6

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.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
1

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();
Chris
  • 22,923
  • 4
  • 56
  • 50
1

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)