Java: why use methods instead of constructor?

Let's say you have a class called Person, and Personhas attributes such as name, id, age, etc. Instead of setting these values ​​in the constructor,

new Person().withName("Lorem").withId("1234").withAge(29)

Where a method withis a method call setand returns an object, e.g.

public Person withAge(int age) {
    this.setAge(age);
    return this;
}

In the current project, I see many such codes, often with 5-10 chained calls to various methods with. What are the advantages of this, instead of setting these values ​​in the constructor?

+4
source share
4 answers

One of the advantages that I see is readability.

If you spread the example

new Person()
.withName("Lorem")
.withId("1234")
.withAge(29)
.withHeight(170)
.withWeight(75)
.withTaxId("1234");

, .

new Person("Lorem","1234",29,170,75,"1234");
+2

, , ?

1)

, , , , null.

 new Person("name", 19);
 new Person("name", 19, address);

 new Person("name", 19, phone);

( ;))

, ( ).

2)

, /, , ,

 new Person("frank", "John", "Emma");
 person.withName("frank").withFather("john").withMother("Emma");

/ , , , . . (, ).

3) , , .

person.setName("name");
person.setAge(19);

person.withName("name").withAge(19);

, , - , , redondant (return this;).

+3

.

, Java- wikipedia::

Author author = AUTHOR.as("author");
create.selectFrom(author)
      .where(exists(selectOne()
                   .from(BOOK)
                   .where(BOOK.STATUS.eq(BOOK_STATUS.SOLD_OUT))
                   .and(BOOK.AUTHOR_ID.eq(author.ID))));

- API, - Builder pattern ( ) ( , API).

API /.


, API- DSL. Martin Fowler , , , ..

+2

, :

1.) . . . Person,

new Person().withName("Loren")

new Person().withName("Loren").withAge(30)

null/default.

2 .

public Person(String name){
  //code
}

public Person(String name, String age){
//code
}

2.) , .

new Person().withName("Loren").withAge(30).withId(567)

,

new Person("Loren", 30, 567)
+1
source

Source: https://habr.com/ru/post/1679695/


All Articles