Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring ResponseEntity : use constructor or static builder?

In a Spring Boot RestController, I'm using the springframework class ResponseEntity to return the response for the endpoint call.

I recently found out there are two ways to instantiate this class.

Using the constructor :

response = new ResponseEntity<MyDto>(myDto, myHeaders, HttpStatus.OK);

Using the static builder :

response = ResponseEntity.ok().headers(myHeaders).body(myDto);

The resulting instance seams to be the same.

I wonder, what are the pros and cons of each ? In which situation should I use preferably one or the other ?

like image 369
Eria Avatar asked May 24 '17 07:05

Eria


2 Answers

With a constructor you have to construct its parameters in advance, whereas with a builder you get to do this in one fluent statement.

// constructor
MultiValueMap<String, String> headers = ...;
ResponseEntity<String> resp = new ResponseEntity(headers, HttpStatus.OK);

// builder
ResponseEntity<String> resp = ResponseEntity.ok()
    .header("header1", "value1")
    .header("header2", "value2")
    .build();

Also, with constructors that have a long list of parameters it gets difficult to see the semantics of each parameter. In those cases I'd prefer a builder.

like image 84
Joeri Leemans Avatar answered Nov 14 '22 23:11

Joeri Leemans


If you have lots of similar endpoints to be defined, like when defining a new API, I have found that using the constructor is better in the long run. Because over time, you end up with repetitive code while using static builders.

Especially in the case of headers; Content-Type, Accept, Encoding etc have to set on all the responses and writing out each in every controller method is cumbersome. Separating such boilerplate code into a separate function is easier with constructors.

That is what I have felt anyway.

like image 40
acchu Avatar answered Nov 14 '22 22:11

acchu