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 ?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With